设计模式-(16)模版模式 (swift版)

一,概念:

  定义一个算法中的操作框架,而将一些步骤延迟到子类中。使得子类可以不改变算法的结构即可重定义该算法的某些特定步骤。(Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure)

 

二,类图

  

  AbstractClass叫做抽象模板,它的方法分为两类:

  • 基本方法:是由子类实现的方法,并且在模板方法被调用。(一般都加上final关键字,防止被覆写)
  • 模板方法:可以有一个或几个,一般是一个具体方法,也就是一个框架,实现对基本方法的调用,完成固定的逻辑。(抽象模板中的基本方法尽量设计为protected类型,符合迪米特法则,不需要暴露的属性或方法尽量不要设置为protected类型。实现类若非必要,尽量不要扩大父类中的访问权限)

三,代码实例

  

class Car {
    func drive() -> Void{
        self.startEngine()
        self.hungUpGear()
        self.loosenTheClutch()
    }
    
    func startEngine() {
        print("start the engine.")
    }
    
    func hungUpGear() {
        print("Hung up the gear.")
    }
    
    func loosenTheClutch() {
        print("Loosen the clutch, go.")
    }
    
}

class BMW: Car {
    override func startEngine() {
        print("start v8 engine.")
    }
    
    override func hungUpGear() {
        print("On the brake pedal, then hung up the gear.")
    }
    
    override func loosenTheClutch() {
        print("Brake pedal up, go.")
    }
}

class BYD: Car {
    override func startEngine() {
        print("start engine.eng~ ")
    }
    
    override func hungUpGear() {
        print("On the clutch, then hung up the gear.")
    }
}

 使用

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let car = BMW()
        car.drive()
    }

}

 

posted on 2018-04-29 11:50  洋子哥哥  阅读(146)  评论(0编辑  收藏  举报