Skip to content

Instantly share code, notes, and snippets.

@bgoetzmann
Last active March 12, 2023 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgoetzmann/112fbe95b4678eaf250f1d2e5c419b27 to your computer and use it in GitHub Desktop.
Save bgoetzmann/112fbe95b4678eaf250f1d2e5c419b27 to your computer and use it in GitHub Desktop.
class Item {
String name
Double price
}
class Cart {
Map items = [:]
Cart addItem(Item item) {
items[item.name] = item
this
}
Cart removeItem(Item item) {
items.remove(item.name)
this
}
}
trait CartCommand {
Cart cart
abstract def execute()
}
class AddItemCommand implements CartCommand {
Item item
AddItemCommand(Cart cart, Item item) {
this.cart = cart
this.item = item
}
def execute() {
cart.addItem(item)
}
}
class RemoveItemCommand implements CartCommand {
Item item
RemoveItemCommand(Cart cart, Item item) {
this.cart = cart
this.item = item
}
def execute() {
cart.removeItem(item)
}
}
def cart = new Cart()
// Command object creation
def command1 = new AddItemCommand(cart, new Item(name: 'Item1', price: 1))
def command2 = new AddItemCommand(cart, new Item(name: 'Item2', price: 1))
def command3 = new RemoveItemCommand(cart, new Item(name: 'Item1', price: 1))
// Invoke commands (invoker part)
def commands = [command1, command2, command3]
commands*.execute()
assert cart.items.keySet() == ['Item2'] as Set
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment