Swift語言之命令模式(Command Pattern)的元編程實現

來源:互聯網
上載者:User

標籤:

今天遇到這樣一個問題,我現在有一個整數數組,如:

var numbers = [3, 7, 12, 9, 200]

現需要對其中的每一個數字都執行一系列相同的加減乘除操作,如對每一個數字都加5乘8再減去1,但是這樣的操作在編譯時間並不確定,需要在運行時由使用者指定;

一看到這個題目,當然就想到了用設計模式中的命令模式來實現;

於是先寫了這樣的一個類:

class Calculator {
private(set) var total = 0 required init(value: Int){ total = value } func add(amount: Int) { total += amount } func substract(amount: Int) { total -= amount } func multiply(amount: Int) { total = total * amount } func divide(amount: Int) { total = total / amount }}

這個類用於實現對某個數執行不同的操作。

下一步中我建立了一個Command類,用於記錄需要執行的操作:

struct Command {        typealias OperationType = (Calculator -> Int -> Void)        let operation: OperationType    let amount: Int        init(operation: OperationType, amount: Int) {        self.operation = operation        self.amount = amount    }        func execute(calculator: Calculator) {        operation(calculator)(amount)    }}

在該類中我定義了一個名為OperationType的類型別名,從定義中可以看出,OperationType類型的執行個體是一個Closure,該Closure接受一個Calculator類型的執行個體,並返回一個類型為Int -> Void的Closure(此Closure的類型就是Calculator中每個方法的類型);

amount為執行那個操作的參數值;

待一切完畢後,由使用者來指定要執行的命令,如將數組numbers中的每一個值加5乘8再減去1,則可以這樣實現:

var commands = [Command]()commands.append(Command(operation: Calculator.add, amount: 5))commands.append(Command(operation: Calculator.multiply, amount: 8))commands.append(Command(operation: Calculator.substract, amount: 1))

OK,執行所有命令:

for number in numbers {    var calculator = Calculator(value: number)        for command in commands {        command.execute(calculator)    }        println("\(number) -> \(calculator.total)")}

這裡是結果:

Swift語言之命令模式(Command Pattern)的元編程實現

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.