1. 程式人生 > >Python基礎設計模式 觀察者模式、營銷模式、

Python基礎設計模式 觀察者模式、營銷模式、

#觀察者模式
class Recetion():
def init(self): #status 動作 狀態
self.oberserList=[] #oberser觀察者
self.status=" "
def attach(self,obj):
self.oberserList.append(obj)
def notify(self): #notify通告
for obj in self.oberserList:
obj.notify()
class Hero():
def init(self,name,recpt):
self.name=name
self.recpt=recpt
def notify(self):
print("%s請注意:請不要玩lol了%s"%(

self.name,self.recpt.status))

class Observer(): #被觀察的
def init(self,name,recpt):
self.name=name
self.recpt=recpt
def notify(self):
print("%s請注意:請不要玩手機了%s"%(self.name,self.recpt.status))
boss=Recetion()
zs=Observer(“張三”,boss)
ls=Observer(“李四”,boss)
ww=Hero(“王五”,boss)
xm=Hero(“小明”,boss)
boss.attach(zs)
boss.attach(ls)
boss.attach(ww)
boss.attach(xm)
boss.status=“老闆娘來了”
boss.notify()

class Boss():
def init(self):
self.obList=[]
self.msg=’’
def attach(self,obj):
self.obList.append(obj)
def notify(self):
for obj in self.obList:
obj.update()
class Market(): #market市場
def init(self,name,boss):
self.name=name
self.boss=boss
def update(self):
print(“市場部的哥們:{} 您好,{}”.format(self.name

,self.boss.msg))
class Tech(): #tech技術
def init(self,name,boss):
self.name=name
self.boss=boss
def update(self):
print(“技術部的哥們:{} 您好,{}”.format(self.name,self.boss.msg))

boss=Boss()
zs=Market(“張三”,boss)
ls=Market(“李四”,boss)
ww=Tech(“王五”,boss)
boss.attach(zs)
boss.attach(ls)
boss.attach(ww)
boss.msg=“下午開會”
boss.notify()

#營銷模式
class CashNormal(): #cash 現金 #normal正常
def getCashMoney(self,money):
return money
class CashRate(): #現金 rate打折
def init(self,rate):
self.rate=rate
def getCashMoney(self,money):
return money * self.rate
class CashReturn():
def init(self,moneyCondition,moneyReturn): #moneycondition 限制返還的最低金額
self.moneyCondition = moneyCondition
self.moneyReturn = moneyReturn
def getCashMoney(self,money):
if money >=self.moneyCondition:
return money-(money//self.moneyCondition)*self.moneyReturn
return money

class Oper():
def init(self,cash):
self.cash=cash
def getCash(self,money):
return self.cash.getCashMoney(money)

zd={}
cashNormal=CashNormal()
cashRate=CashRate(0.8)
cashReturn=CashReturn(400,50)
zd[1]=Oper(cashNormal)
zd[2]=Oper(cashRate)
zd[3]=Oper(cashReturn)
money=int(input(“請輸入現金”))
cl=int(input(“請輸入收費策略”))
if cl in zd:
print(zd[cl].getCash(money))
else:
print(zd[1].getCash(money))