Python的設計模式學習

1.工廠模式html

#encoding=utf-8
__author__ = 'kevinlu1010@qq.com'

class ADD():
    def getResult(self,*args):
        return args[0]+args[1]
class SUB():
    def getResult(self,*args):
        return  args[0]-args[1]
class MUL():
    def getResult(self,*args):
        return  args[0]*args[1]
class DIV():
    def getResult(self,*args):
        try:
            return  args[0]/args[1]
        except:return 0
class UNKnow():
    def getResult(self,op1,op2):
        return 'unknow'
class Factory():
    Classes={'+':ADD,'-':SUB,'*':MUL,'/':DIV}
    def getClass(self,key):
        return self.Classes[key]() if key in self.Classes else  UNKnow()

if __name__=='__main__':
    key='+'
    op1=91
    op2=45
    factory=Factory()
    c=factory.getClass(key)
    r=c.getResult(op1,op2)
    print r

 

工廠模式會建立一個工廠類,該類會根據實例化時的輸入參數返回相應的類。Factory這個類會根據輸入的key,返回相應的加,減,乘或除類。app

2.策略模式ide

 

#encoding=utf-8
__author__ = 'kevinlu1010@qq.com'

class Base():
    def getPrice(self,price):
        pass
class Origin(Base):
    def getPrice(self,price):
        return price
class Vip(Base):
    def getPrice(self,price):
        return price*0.8
class Sale(Base):
    def getPrice(self,price):
        return price-price/100*20
class Context():
    def __init__(self,c):
        self.c=c
    def getPrice(self,price):
        return self.c.getPrice(price)

if __name__=='__main__':
    strategy={}
    strategy[0]=Context(Origin())
    strategy[1]=Context(Vip())
    strategy[2]=Context(Sale())
    price=485
    s=2
    price_last=strategy[s].getPrice(price)
    print price_last

 

 

策略模式中,系統會根據不一樣的策略,返回不一樣的值,例如超市裏面,會有不一樣的計價方法,例如普通客戶會以原價來計價,vip會打八折,活動促銷時滿10020,這裏就有三種策略,在系統中,輸入原價和採起的策略方式,系統就會根據選擇的策略,計算消費者最終須要支付的金額。策略模式與工廠模式相似,例如上面的例子也能夠用工廠模式來實現,就是新建三個類,每一個類都有一個計價的方法。而策略模式和工廠模式的區別是策略模式更適用於策略不一樣的情景,也就是類中的方法不一樣,而工廠模式更適合類不一樣的情景。spa

 單例模式code

class Singleton(object):
    def __new__(type, *args, **kwargs):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type, *args, **kwargs)
        return type._the_instance
class MySin(Singleton):
    b=0
    def __init__(self):
        print self.b
        if not self.b:self.b+=1
        print self.b
        self.a=[1]
    def change(self):
        self.a.append(2)

c1=MySin()
c1.a.append(3)
c2=MySin()
print c1.a
c1.change()
print c2.a

 

參考:http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.htmlhtm

相關文章
相關標籤/搜索