码迷,mamicode.com
首页 > 编程语言 > 详细

Python的设计模式学习

时间:2014-07-16 22:56:35      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   html   

1.工厂模式

#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,返回相应的加,减,乘或除类。

2.策略模式

 

#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,这里就有三种策略,在系统中,输入原价和采取的策略方式,系统就会根据选择的策略,计算消费者最终需要支付的金额。策略模式与工厂模式类似,例如上面的例子也可以用工厂模式来实现,就是新建三个类,每个类都有一个计价的方法。而策略模式和工厂模式的区别是策略模式更适用于策略不同的情景,也就是类中的方法不同,而工厂模式更适合类不同的情景。

 

参考:http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

Python的设计模式学习,布布扣,bubuko.com

Python的设计模式学习

标签:style   blog   http   color   os   html   

原文地址:http://www.cnblogs.com/Xjng/p/3835422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!