命令模式二

接收者 TerisMachine

class TerisMachine: NSObject {
    func toLeft() {
        print("向左")
    }
    func toRight() {
        print("向右")
    }
    func toTransform() {
        print("变形")
    }
}

命令接口 TMCommandProtocol

protocol TMCommandProtocol {
    func execute()
}

命令

class TMLeftCommand: TMCommandProtocol {
    private var tm : TerisMachine;
    init(tm:TerisMachine) {
        self.tm = tm;
    }
    
    func execute() {
        self.tm.toLeft();
    }
}
class TMRightCommand: TMCommandProtocol {
    private var tm : TerisMachine;
    init(tm:TerisMachine) {
        self.tm = tm;
    }
    
    func execute() {
        self.tm.toRight();
    }
}
class TMTransformCommand: TMCommandProtocol {
    private var tm : TerisMachine;
    init(tm:TerisMachine) {
        self.tm = tm;
    }
    
    func execute() {
        self.tm.toTransform();
    }
}

请求者 TerisMachineManager

class TerisMachineManager: NSObject {
    
    private var left    : TMLeftCommand;
    private var right   : TMRightCommand;
    private var transform : TMTransformCommand;
    private var tm : TerisMachine;
    private var commont  = Array();

    init(tm:TerisMachine,left:TMLeftCommand,right:TMRightCommand,transform:TMTransformCommand) {
        self.tm = tm;
        self.left = left;
        self.transform = transform;
        self.right = right;
    }
    
    //具体的业务逻辑
    func toLeft() {
        self.left.execute();
        self.commont.append(TMLeftCommand(tm: self.tm));
    }
    func toRight() {
        self.right.execute();
        self.commont.append(TMRightCommand(tm: self.tm));
    }
    func toTransform() {
        self.transform.execute();
        self.commont.append(TMTransformCommand(tm: self.tm));
    }
    
    func undo() {
        print("撤销")
        if self.commont.count > 0 {
            self.commont.removeLast().execute();
            
        }
    }
}

你可能感兴趣的:(命令模式二)