Today I have a problem with an array of integers, such as:
var numbers = [3, 7, 12, 9, 200]
It is now necessary to perform a series of identical subtraction operations on each of these numbers, such as adding 5 times 8 to each number minus 1, but such operations are not deterministic at compile time and need to be specified by the user at run time;
When you see this topic, of course, I think of the design pattern in the command mode to achieve;
So first wrote a class like this:
Class Calculator {
var total = 0 required init (value:int) { = value } func Add (amount:int) {
+= Amount } func substract (amount:int) { -= amount } func Multiply ( Amount:int) { = total * amount } func-Divide (amount:int) {= total/ amount
}}
This class is used to implement different operations on a number.
In the next step I created a command class that records what needs to be done:
struct Command { = (Calculator, Int, Void) let operation:operationtype let amount:in T Init (Operation:operationtype, amount:int) { = operation = amount } func Execute (calculator:calculator) { operation (Calculator) (amount) } }
In this class I define a type alias named Operationtype, as you can see from the definition that an instance of the Operationtype type is a closure that accepts an instance of a calculator type and returns a type of INT- > void Closure (the type of this closure is the type of each method in Calculator);
Amount the value of the parameter to perform that operation;
After all is done, the user specifies the command to execute, such as adding 5 times 8 to each value in the array numbers and subtracting 1, this can be done:
var commands =581))
OK, execute all commands:
for inch numbers { var calculator = Calculator (value:number) for in Commands { Command.Execute (Calculator) } println ("\ (number)} \ ( calculator.total)}
Here is the result:
A meta-programming implementation of command pattern for swift language