Python常用设计模式(2)

上次说了常用设计模式中的单例模式和工厂模式,今天说说策略模式和观察者模式。

3. 策略模式

策略指的就是为了达到某一目的而采取的多种手段或者方法。

为了实现软件设计,对象可能会用到多种多样的算法(逻辑)。这些算法甚至会经常改变。如 果将这些算法都硬编码到对象中,将会使得对象本身变得臃肿不堪。

策略模式很好的实现了将算法与本身对象解耦,从而避免出现上述的问题。

因此策略模式可以定义为: 定义一系列算法(逻辑),将每一个算法封装起来(一个算法创建 一个类),并让它们可以相互替换。

此模式让算法的变化,不会影响到使用算法的客户. 策略模式的结构

策略模式包含以下3个角色:
Context(环境类)
Strategy(抽象策略类)
ConcreteStrategy(具体策略类)

class CashNOmal:
    def accept_money(self,money):
        return money
class CashRate:
    """打折"""
    def __init__(self,rate):
        self.rate=rate
    def accept_money(self,money):
        return money*self.rate
class CashReturn:
    """满减"""
    def __init__(self,condition,ret):
        self.condition=condition #满减条件
        self.ret=ret #满减金额
    def accept_money(self,money):
        # if money>=self.condition:
        #     return money-(money//self.condition)*self.ret
        # else:
        #     return money
        return money - (money // self.condition) * self.ret
class Context:
    """调用策略"""
    def __init__(self,cs):
        self.cs=cs

    def get_result(self,money):
        return self.cs.accept_money(money)

if __name__ =="__main__":
    zd={}
    zd[1]=Context(CashNOmal()) #正常支付
    zd[2]=Context(CashRate(0.8)) #打折
    zd[3]=Context(CashReturn(300,50)) #满减
    culue = int(input("请输入策略:"))
    if culue in zd:
        cs=zd[culue]
    else:
        cs=zd[1]
    money=float(input("请输入钱:"))
    print(cs.get_result(money))

class CashNormal():
    def accept_money(self,money):
        return money
class CashRate():
    def __init__(self,rate):
        self.rate=rate

结果:

第一种:
请输入策略:1
请输入钱:500
500.0

第二种:
请输入策略:2
请输入钱:500
400.0

第三种:
请输入策略:3
请输入钱:500
450.0

4. 观察者模式

观察者模式:又叫发布订阅模式,定义了一种一对多的依赖关系,让多个观察者对象同时监
听某一个主题对象,这个主题对象的状态发生变化时,会通知所有观察者对象,是他们能自
动更新自己。

具体应用场景:
事件驱动系统是观察者模式的例子。在这种系统中,监听者被用于监听特定事
件。监听者正在监听的事件被创建出来时,就会触发它们。这个事件可以是键入
(键盘的)某个特定键、移动鼠标或者其他。事件扮演发布者的角色,监听者则
扮演观察者的角色。在这里,关键点是单个事件(发布者)可以关联多个监听者
(观察者)

class Monitor:
    """通知者----》班长----》管理观察者"""
    def __init__(self):
        self.observers=[] #保存观察者对象
        self.status=" "  #表示状态
    def attach(self,observer):
        """绑定每一个观察者"""
        self.observers.append(observer)
    def notify(self):
        """通知每一个观察者"""
        for observer in self.observers:
            observer.update()
class SleepStudentobserver:
    """观察者"""
    def __init__(self,name,monitor):
        self.name=name #被观察者姓名
        self.monitor=monitor #绑定通知者

    def update(self):
        print("{},{}赶紧起来学习".format(self.monitor.status,self.name))

if __name__ == "__main__":
    monitor=Monitor()
    obsercer1=SleepStudentobserver("zs",monitor)
    obsercer2=SleepStudentobserver("ls",monitor)
    monitor.attach(obsercer1)
    monitor.attach(obsercer2)
    monitor.status="老师又来了"
    monitor.notify()

结果:

老师又来了,zs赶紧起来学习
老师又来了,ls赶紧起来学习

*end~~~~*

发布了36 篇原创文章 · 获赞 49 · 访问量 2882

猜你喜欢

转载自blog.csdn.net/HENG302926/article/details/103721301