Python基础设计模式 观察者模式、营销模式、

2021-11-22 15:54:32 浏览数 (1)

代码语言:javascript复制
#观察者模式
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))
    ```

0 人点赞