Python
設計模式
責任鏈模式
class buySomething:
def __init__(self):
self.Money = 0
def SetPrice(self, Money):
self.Money = Money
def SendRequest(self, handler):
handler.OktoBuy(self.Money)
class Handler:
def __init__(self):
self.Level = None
def OktoBuy(self):
pass
def SetNextLevelHandler(self, level):
self.Level = level
class BuyItLevel1(Handler):
def OktoBuy(self, request):
if 0<=request<=50:
print('Level 1 Ok buy')
else:
self.Level.OktoBuy(request)
class BuyItLevel2(Handler):
def OktoBuy(self, request):
if 51<=request<=100:
print('Level 2 Ok buy')
else:
self.Level.OktoBuy(request)
class BuyItLevel3(Handler):
def OktoBuy(self, request):
if 101<=request<=200:
print('Level 3 Ok buy')
else:
self.Level.OktoBuy(request)
h1 = BuyItLevel1()
h2 = BuyItLevel2()
h3 = BuyItLevel3()
h1.SetNextLevelHandler(h2)
h2.SetNextLevelHandler(h3)
b = buySomething()
print('Price : 30')
b.SetPrice(30)
b.SendRequest(h1)
print('Price : 51')
b.SetPrice(51)
b.SendRequest(h1)
print('Price : 115')
b.SetPrice(115)
b.SendRequest(h1)
程式碼說明
handler是用來寫確認的介面,level1、level2、level3是用來寫個別的等級,setNextLevel是設定下一個層級,buySomething是用來寫買東西的內容,並提出申請。
留言
張貼留言