设计模式之 Template Method 模板方法:Swift 实现

Template Method 模板方法

对于一项事务,把主要的流程拆分为一些步骤,父类中的模板方法调用这些步骤来完成任务,不同的子类不能修改模板方法,但可以修改小步骤的具体实现。


The super class define an algorithm structure, and the subclass can override the method without changing the structure. Depart an algorithm into a series of step, and rewrite these step as method, then call these method in the template method.

超类定义了一个算法框架,子类可以在不改动框架的情况下依据需要来重写细节方法。把算法拆分为一系列的步骤,把这些步骤写成方法,然后可以在模板方法中调用这些方法。

模板方法
注意:抽象父类定义了模板方法框架,具体的实现类(子类)不能重写模板方法,只修改实现细节。

// Abstract class
class House {
	// Use final to prevent the subclass override the template method.
    final func build(){
        makeRoot()
        makeWall()
        makeWindows()
        makeRoof()
    }
    
    func makeRoot() {
        print("Use cement to construct root.")
    }
    
    func makeWall() {
        print("Add white wall")
    }
    
    func makeWindows() {
        print("Add window")
    }
    
    func makeRoof() {
        print("Add smooth roof")
    }
}

// Concrete class A
class EastenHouse: House {
    override func makeWall() {
        print("Add red wall.")
    }
    
    override func makeWindows() {
        print("Add wooden windows.")
    }
    
    override func makeRoof() {
        print("Add wooden roof.")
    }
    
}

// Concrete class B
class WestenHouse: House {
    
    override func makeWindows() {
        print("Add iron windows")
    }
    
    
    override func makeRoof() {
        print("Add cement roof")
    }
}

let house = EastenHouse()
house.build()

let houseB = WestenHouse()
houseB.build()

以上代码中,house 的建造方法定义为 final,不能被重写,并且把操作拆分为一些小步骤,先安装地基,接着是墙,然后是窗户,最后是屋顶,子类有 东方的屋子、西方的屋子,子类在安装窗户和屋顶的实现上是不一样的(个性化的定制),所以它们各自重写父类对应的步骤方法。各个子类的模板方法(建造房子的框架)都来自同一个父类,并且不能被重写。

最后,不同子类建造出来的房子虽说同样符合父类模板方法的规定,但表现出的特征也会不一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值