Python设计模式-策略模式

来源:互联网 发布:linux找不到mysql命令 编辑:程序博客网 时间:2024/05/22 10:34

Python设计模式-策略模式

代码基于3.5.2,代码如下;

#coding:utf-8#策略模式class sendInterface():    def send(self,value):        raise NotImplementedErrorclass phone(sendInterface):    def send(self,value):        print("phone send:",value)class email(sendInterface):    def send(self,value):        print("email send:",value)class weixin(sendInterface):    def send(self,value):        print("weixin send:",value)class content():    def __init__(self,sendMethod):        self.sendMethod = sendMethod    def send(self,value):        self.sendMethod.send(value)if __name__ == "__main__":    ph = content(phone())    ph.send("回家吃饭")    em = content(email())    em.send("回家吃饭")    wx = content(weixin())    wx.send("回家吃饭")

策略模式的分析与解读

策略模式

策略模式,它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。桥接模式与策略模式在结构上高度同构,我们要从使用意图上区分两种模式:桥接模式解决抽象角色和实现角色都可以扩展的问题,策略模式解决算法切换和扩展的问题。

代码解读

1、先定义方法的实现接口类sendInterface,让所有继承该类的类实现send方法;2、通过继承sendInterface类,分别定义了phone、email和weixin三个类,并实现了各自不同的send()方法;3、通过定义content类,在初始化时,传入对应的方法类,然后统一使用send()方法调用方法类对应实现的send()方法,从而完成通过content完成不同方法的调用。

代码运行结果如下:

”’
phone send: 回家吃饭
email send: 回家吃饭
weixin send: 回家吃饭
”’

策略模式应用场景:

1、策略模式比较经常地需要被替换时,可以使用策略模式。如在付账问题时,会遇到刷卡、某宝支付等问题时,可以考虑策略模式。

优缺点分析

优点

1、各个策略可以自由切换;这也是依赖抽象类设计接口的好处之一;2、减少冗余代码;3、扩展性好;4、优化了单元测试,每个实现方法的类都可以进行自己的单独测试;

缺点

1、项目比较庞大时,策略模式使用多时,不便于维护;2、策略的使用方必须知道有哪些策略,才能决定使用哪一个策略,这与迪米特法则违背。

备注

迪米特法则:如果两个类不必彼此直接通信,那么这两个类就不应当发生直接的相互作用。如果其中一个类需要调用另一个类的某一个方法的话,可以通过第三者转发这个调用。策略模式也可与简单工厂模式相互配合使用:
    class sendInterface():        def send(self,value):            raise NotImplementedError    class phone(sendInterface):        def send(self,value):            print("phone send:",value)    class email(sendInterface):        def send(self,value):            print("email send:",value)    class weixin(sendInterface):        def send(self,value):            print("weixin send:",value)    class contentFactory():        sendMethod = None        def createFactory(self,type):            if type == "phone":                self.sendMethod = phone()            elif type == "email":                self.sendMethod = email()            elif type == "weixin":                self.sendMethod = weixin()        def send(self,value):            self.sendMethod.send(value)    if __name__ == "__main__":        factory = contentFactory()        factory.createFactory("phone")        factory.send("回家吃饭")        factory.createFactory("email")        factory.send("回家吃饭")        factory.createFactory("weixin")        factory.send("回家吃饭")
原创粉丝点击