模板方法模式(*IoC反向呼叫之概念)
定義多个接口之抽象类,可讓繼承不同子类來实现其接口以達到不同操作行為,且依需求設計模板方法調用必要接口轉而反向呼叫(IoC)子類實作之方法,此有助于减少代码之重用且可避免重复工作,另可達到多態設計的弱引用。
UML类图
- AbstractCls抽象類: 定义操作步驟之各接口,这些接口必須被不同具体子类來實作之其行為,而tmplate_method()模板方法則為依需求而調用所定义操作步驟之各接口,在運行時會轉而反向呼叫(IoC)繼承子類之實作行為。
- ConcreteCls具体子類:实现AbstractCls抽象類定义主要接口之操作行為。
示例:
# -*- coding: UTF-8 -*-
from abc import ABCMeta,abstractmethod
class AbstractCls: #抽象類
def __init__(self):
pass
@abstractmethod
def operation1(self):
pass
@abstractmethod
def operation2(self):
pass
def template_method(self): #模板方法
print ("Defining the Algorithm: operation1 follows after operation2")
self.operation2()
self.operation1()
class ConcreteCls(AbstractCls): #具体子类
def operation1(self):
print ("My Concrete Operation1")
def operation2(self):
print ("Operation 2 remains same")
class Client: #客户端類
def mian(self):
self.concreate = ConcreteCls()
self.concreate.template_method()
if __name__==’__main__’:
client = Client()
client.mian()
輸出:
Defining the Algorithm: operation1 follows after operation2
Operation 2 remains same
My Concrete Operation1
應用示例:旅行社安排出游
# -*- coding: UTF-8 -*-
from abc import ABCMeta,abstractmethod
class Trip: #抽象類
def __init__(self):
pass
@abstractmethod
def setTransport(self):
pass
@abstractmethod
def day1(self):
pass
@abstractmethod
def day2(self):
pass
@abstractmethod
def day3(self):
pass
@abstractmethod
def returnHome(self):
pass
def itinerary(self): #模板方法
self.setTransport()
self.day1()
self.day2()
self.day3()
self.returnHome()
class VeniceTrip(Trip): #具体子类1
def setTransport(self):
print ("Take a boat and find your way in the Grand Canal")
def day1(self):
print ("Visit St Mark Basilica in St Mark Square")
def day2(self):
print ("Enjoy the food near the Rialto Bridge")
def day3(self):
print ("Get souvenirs for friends and get back")
def returnHome(self):
print ("Get souvenirs for friends and get back")
class MaldivesTrip(Trip): #具体子类2
def setTransport(self):
print ("On foot,on any island,Wow")
def day1(self):
print ("Enjoy the marine life of Banana Reef")
def day2(self):
print ("Go for the water sports and snorkelling")
def day3(self):
print ("Relax on the beach and enjoy the sun")
def returnHome(self):
print ("Dont feel like leaving the beach..")
class TravelAgency: #客户端類
def arrange_trip(self):
choice =input("What kind of place you like to go historical or to a beach:")
if choice =="historical":
self.trip = VeniceTrip()
self.trip.itinerary()
if choice == "beach":
self.trip = MaldivesTrip()
self.trip.itinerary()
if __name__==’__main__’:
TravelAgency().arrange_trip()
輸出:
What kind of place you like to go historical or to a beach:beach
On foot,on any island,Wow
Enjoy the marine life of Banana Reef
Go for the water sports and snorkelling
Relax on the beach and enjoy the sun
Dont feel like leaving the beach..
模板方法-钩子
1.1在抽象类中声明的各種接口,它通常須由不同繼承子類來实现。
1.2 当子类实现抽象類中之接口,并且当基类的模板方法調用接口時實則會反向呼叫(IoC)繼承子類之操作行為,此即為钩子。