[python]设计模式

来源:互联网 发布:java stackoverflow 编辑:程序博客网 时间:2024/06/13 10:35

需要说明:java跟python在思维模式上并不一样,java利用接口以及多态可以实现很多抽象上的东西,而python不行,其实以下很多设计模式写法并不适用也没有必要,更多是为了对比和帮助理解这些设计模式,毕竟设计模式的核心是解耦。

 

1.单例模式

复制代码
#-*- encoding=utf-8 -*-class Singleton(object):    def __new__(cls, *args, **kw):        if not hasattr(cls, '_instance'):            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)        return cls._instancea = Singleton()b = Singleton()print id(a)print id(b)
复制代码

 

2.模板模式

复制代码
#coding:utf-8class CaffeineBeverageWithHook(object):    def prepareRecipe(self):        self.boilWater()        self.brew()        self.pourInCup()        if self.customerWantsCondiments():            self.addCondiments()    def brew(self):        print "start brew."    def addCondiments(self):        pass    def boilWater(self):        print "start boilWater."    def pourInCup(self):        print "Pour into cup"    def customerWantsCondiments(self):        return Falseclass CoffeeWithHook(CaffeineBeverageWithHook):    def brew(self):        print "Dripping coffee through filter."    def addCondiments(self):        print "Add Sugar and Milk."    def customerWantsCondiments(self):        return Trueif __name__ == '__main__':    coffeeWithHook = CoffeeWithHook()    coffeeWithHook.prepareRecipe()
复制代码

 

3.适配器模式

复制代码
#coding: utf-8class Target(object):    def request(self):        print "this is target.request method."class Adaptee(object):    def special_request(self):        print "this is Adaptee.special_request method."class Adapter(object):    def __init__(self):        self.special_req = Adaptee()    def request(self):        self.special_req.special_request()if __name__ == '__main__':    adapter = Adapter()    adapter.request()
复制代码

 4.策略模式:在策略模式中遵循依赖倒置原则,使得策略在代码运行时生效

复制代码
# -*- coding: utf-8 -*-class IStrategy(object):    def doSomething(self):        returnclass ConcreteStrategy1(IStrategy):    def doSomething(self):        print "concreteStrategy 1"class ConcreteStrategy2(IStrategy):    def doSomething(self):        print "concreteStrategy 2"class Context(object):    def __init__(self, concreteStrategy):        self.strategy = concreteStrategy()    def execute(self):        self.strategy.doSomething()if __name__ == '__main__':    print "-----exec concreteStrategy 1-----"    context = Context(ConcreteStrategy1)    context.execute()    print "-----exec concreteStrategy 2-----"    context = Context(ConcreteStrategy2)    context.execute()
复制代码

 

5.工厂模式

复制代码
#coding:utf-8import sysreload(sys)sys.setdefaultencoding("utf-8")class XMobile(object):    def __init__(self, factory):        self._factory = factory    def order_mobile(self, brand):        mobile = self._factory.create_mobile(brand)        mobile.special_design()        mobile.hardware()        mobile.software()        mobile.combine()        mobile.box()class MobileFactory(object):    def create_mobile(self, brand):        if brand == "Huawei":            mobile = HuaweiProductLine(brand)        elif brand == "Xiaomi":            mobile = XiaomiProductLine(brand)        elif brand == "Meizu":            mobile = MeizuProductLine(brand)        return mobileclass MobileProductLine(object):    def __init__(self, brand):        self.brand = brand    def hardware(self):        print "准备硬件"    def software(self):        print "准备软件"    def combine(self):        print "合并手机"    def box(self):        print "封装手机"class HuaweiProductLine(MobileProductLine):    def __init__(self, brand):        super(HuaweiProductLine,self).__init__(brand)    def special_design(self):        print "使用Haisi CPU"class XiaomiProductLine(MobileProductLine):    def __init__(self, brand):        super(XiaomiProductLine,self).__init__(brand)    def special_design(self):        print "使用MIUI"class MeizuProductLine(MobileProductLine):    def __init__(self, brand):        super(MeizuProductLine,self).__init__(brand)    def special_design(self):        print "使用Flyme"if __name__ == '__main__':    mobileFactory = MobileFactory()    xmobile = XMobile(mobileFactory)    xmobile.order_mobile("Huawei")
复制代码

 

6.观察者模式

复制代码
#coding:utf-8class Subject(object):    def __init__(self):        self.obs_list = []    # observer对象    def addObserver(self, obs):        self.obs_list.append(obs)    def delObserver(self, obs):        self.obs_list.pop(obs)    def notifyObserver(self):        for obs in self.obs_list:            obs.update()    def doSomething(self):        returnclass ConcreteSubject(Subject):    def __init__(self):        super(ConcreteSubject, self).__init__()    def doSomething(self):        self.notifyObserver()class Observer(object):    def update(self):        returnclass ConcreteObserver1(Observer):    def update(self):        print "观察者1收到信息,并进行处理。"class ConcreteObserver2(Observer):    def update(self):        print "观察者2收到信息,并进行处理。"if __name__ == '__main__':    concreteSubject = ConcreteSubject()    concreteSubject.addObserver(ConcreteObserver1())    concreteSubject.addObserver(ConcreteObserver2())    concreteSubject.doSomething()
复制代码

 

7.外观模式

外观模式是将一系列接口进行封装,使得外层调用更加方便,因此不作说明

原文链接:http://www.cnblogs.com/alexkn/p/5628612.html

0 0
原创粉丝点击