Last active
March 12, 2023 14:21
-
-
Save bgoetzmann/112fbe95b4678eaf250f1d2e5c419b27 to your computer and use it in GitHub Desktop.
Used in this article: https://medium.com/@bgoetzmann/modèle-de-conception-commande-en-langage-groovy-9bea26b47d6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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