Design Patterns - (16) Template Patterns (Swift Version)

One, the concept:

  Define the framework of operations in an algorithm, while deferring some steps to subclasses. Allows subclasses to redefine certain steps of the algorithm without changing the structure of the algorithm. (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)

 

2. Class diagram

  

  AbstractClass is called abstract template, and its methods are divided into two categories:

  • Base methods: are methods implemented by subclasses and are called in template methods. (usually add the final keyword to prevent overwriting)
  • Template method: There can be one or several, usually a specific method, that is, a framework, which implements the call to the basic method and completes the fixed logic. (The basic methods in the abstract template should be designed as protected types as much as possible, in line with the Law of Demeter, and properties or methods that do not need to be exposed should not be set as protected types. If the implementation class is not necessary, try not to expand the access rights in the parent class)

Third, the code example

  

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 WORLD: Car {
    override func startEngine() {
        print("start engine.eng~ ")
    }
    
    override func hungUpGear() {
        print("On the clutch, then hung up the gear.")
    }
}

 use

class ViewController: UIViewController {

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

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325020658&siteId=291194637