您的位置:首页 > 编程语言 > Python开发

Python的设计模式学习

2014-07-10 11:56 453 查看
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会打八折,活动促销时满100减20,这里就有三种策略,在系统中,输入原价和采取的策略方式,系统就会根据选择的策略,计算消费者最终需要支付的金额。策略模式与工厂模式类似,例如上面的例子也可以用工厂模式来实现,就是新建三个类,每个类都有一个计价的方法。而策略模式和工厂模式的区别是策略模式更适用于策略不同的情景,也就是类中的方法不同,而工厂模式更适合类不同的情景。

单例模式

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


参考:/content/3856069.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: