1. 程式人生 > >設計模式-(16)模版模式 (swift版)

設計模式-(16)模版模式 (swift版)

基本 protect pla without 屬性 模板方法 分享圖片 dal ont

一,概念:

  定義一個算法中的操作框架,而將一些步驟延遲到子類中。使得子類可以不改變算法的結構即可重定義該算法的某些特定步驟。(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()
    }

}

設計模式-(16)模版模式 (swift版)