python設計模式實現__python

來源:互聯網
上載者:User

本文轉載自http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html,並刪除了部分內容

《大話設計模式》Python版代碼實現

一、簡單原廠模式

模式特點:工廠根據條件產生不同功能的類。

程式執行個體:四則運算計算機,根據使用者的輸入產生相應的運算類,用這個運算類處理具體的運算。

代碼特點:C/C++中的switch...case...分支使用字典的方式代替。

     使用異常機制對除數為0的情況進行處理。

class Operation:    def GetResult(self):        passclass OperationAdd(Operation):    def GetResult(self):        return self.op1+self.op2class OperationSub(Operation):    def GetResult(self):        return self.op1-self.op2class OperationMul(Operation):    def GetResult(self):        return self.op1*self.op2class OperationDiv(Operation):    def GetResult(self):        try:            result = self.op1/self.op2            return result        except:            print "error:divided by zero."            return 0class OperationUndef(Operation):    def GetResult(self):        print "Undefine operation."        return 0class OperationFactory:    operation = {}    operation["+"] = OperationAdd();    operation["-"] = OperationSub();    operation["*"] = OperationMul();    operation["/"] = OperationDiv();    def createOperation(self,ch):                if ch in self.operation:            op = self.operation[ch]        else:            op = OperationUndef()        return opif __name__ == "__main__":    op = raw_input("operator: ")    opa = input("a: ")    opb = input("b: ")    factory = OperationFactory()    cal = factory.createOperation(op)    cal.op1 = opa    cal.op2 = opb    print cal.GetResult()

 

二、策略模式

模式特點:定義演算法家族並且分別封裝,它們之間可以相互替換而不影響用戶端。

程式執行個體:商場收銀軟體,需要根據不同的銷售策略方式進行收費

代碼特點:不同於同例1,這裡使用字典是為了避免關鍵字不在字典導致bug的陷阱。

class CashSuper:    def AcceptCash(self,money):        return 0class CashNormal(CashSuper):    def AcceptCash(self,money):        return moneyclass CashRebate(CashSuper):    discount = 0    def __init__(self,ds):        self.discount = ds    def AcceptCash(self,money):        return money * self.discountclass CashReturn(CashSuper):    total = 0;    ret = 0;    def __init__(self,t,r):        self.total = t        self.ret = r    def AcceptCash(self,money):        if (money>=self.total):            return money - self.ret        else:            return moneyclass CashContext:    def __init__(self,csuper):        self.cs = csuper    def GetResult(self,money):        return self.cs.AcceptCash(money)if __name__ == "__main__":    money = input("money:")    strategy = {}    strategy[1] = CashContext(CashNormal())    strategy[2] = CashContext(CashRebate(0.8))    strategy[3] = CashContext(CashReturn(300,100))    ctype = input("type:[1]for normal,[2]for 80% discount [3]for 300 -100.")    if ctype in strategy:        cc = strategy[ctype]    else:        print "Undefine type.Use normal mode."        cc = strategy[1]    print "you will pay:%d" %(cc.GetResult(money))

三、裝飾模式

模式特點:動態地為對象增加額外的職責

程式執行個體:展示一個人一件一件穿衣服的過程。

代碼特點:無

class Person:    def __init__(self,tname):        self.name = tname    def Show(self):       print "dressed %s" %(self.name)class Finery(Person):    componet = None    def __init__(self):        pass    def Decorate(self,ct):        self.componet = ct    def Show(self):    if(self.componet!=None):        self.componet.Show()class TShirts(Finery):    def __init__(self):        pass    def Show(self):        print "Big T-shirt "        self.componet.Show()class BigTrouser(Finery):    def __init__(self):        pass    def Show(self):        print "Big Trouser "        self.componet.Show()if __name__ == "__main__":    p = Person("somebody")    bt = BigTrouser()    ts = TShirts()    bt.Decorate(p)    ts.Decorate(bt)    ts.Show()

四、代理模式

模式特點:為其他對象提供一種代理以控制對這個對象的訪問。

程式執行個體:同模式特點描述。

代碼特點:無

class Interface :    def Request(self):    return 0class RealSubject(Interface):     def Request(self):        print "Real request."class Proxy(Interface):    def Request(self):        self.real = RealSubject()        self.real.Request()if __name__ == "__main__":    p = Proxy()    p.Request()

五、Factory 方法模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.