设计模式-模板方法模式
1.定义
模板方法模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使用子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
2.使用场景
代码的重复使用的地方
3.代码实现
先定义一个基类(抽象类)所有子类的基础,它定义了子类的大致行为。
子类具体实现具体行为实现
3.1Java代码实现
实现放学回家的步骤
1.出校门
2.坐公交
3.走到家门
分别实现从三中回家和从四中回家
先定义一个基类
abstract class GoHome{
final void run(){
outOfSchool(); // 出校门
takeTheBus(); //坐公交
walkHome(); //走到家门
}
// 因为出校门这个动作不管是从三种回家还是从四中回家都是一样的
public void outOfSchool(){
System.out.println("出校门");
}
public void takeTheBus(){}
public void walkHome(){}
}
从三中回家实现子类
class SanZhong extends GoHome{
public void takeTheBus(){
System.out.println("做5路公交车");
}
public void walkHome(){
System.out.println("走300米到家门");
}
}
从四中回家实现子类
class SiZhong extends GoHome{
public void takeTheBus(){
System.out.println("做6路公交车");
}
public void walkHome(){
System.out.println("走500米到家门");
}
}
运行类
class Main{
public static void main(String [] args){
GoHome sanZhong = new SanZhong();
GoHome siZhong = new SiZhong();
System.out.println("三中");
sanZhong.run();
System.out.println("四中");
siZhong.run();
}
}
运行结果:
三中
出校门
做5路公交车
走300米到家门
四中
出校门
做6路公交车
走500米到家门
3.2python代码实现
基类
import abc #利用abc模块实现抽象类
class GoHome:
def outOfSchool(self):
print("出校门")
@abc.abstractmethod #定义抽象方法,子类必须重写此方法
def takeTheBus(self):
pass
@abc.abstractmethod #定义抽象方法,子类必须重写此方法
def walkHome(self):
pass
def run(self):
self.outOfSchool()
self.takeTheBus()
self.walkHome()
从三中回家实现子类
class SanZhong(GoHome):
def takeTheBus(self):
print("做5路公交车")
def walkHome(self):
print("走300米到家门")
从四中回家实现子类
class SiZhong(GoHome):
def takeTheBus(self):
print("做6路公交车")
def walkHome(self):
print("走500米到家门")
运行
sanzhong = SanZhong()
sizhong = SiZhong()
print("三中")
sanzhong.run()
print("四中")
sizhong.run()
运行结果:
三中
出校门
做5路公交车
走300米到家门
四中
出校门
做6路公交车
走500米到家门