Python的設計模式學習

2021-09-06 16:51:05 字數 2748 閱讀 7995

1.工廠模式

#

encoding=utf-8

__author__ = '

[email protected]

'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

0class

unknow():

defgetresult(self,op1,op2):

return

'unknow

'class

factory():

classes=

defgetclass(self,key):

return self.classes[key]() if key in self.classes else

unknow()

if__name__=='

__main__':

key='+'

op1=91op2=45factory=factory()

c=factory.getclass(key)

r=c.getresult(op1,op2)

print r

工廠模式會建立乙個工廠類,該類會根據例項化時的輸入引數返回相應的類。factory

這個類會根據輸入的key

,返回相應的加,減,乘或除類。

2.策略模式

#

encoding=utf-8

__author__ = '

[email protected]

'class

base():

defgetprice(self,price):

pass

class

origin(base):

defgetprice(self,price):

return

price

class

vip(base):

defgetprice(self,price):

return price*0.8

class

sale(base):

defgetprice(self,price):

return price-price/100*20

class

context():

def__init__

(self,c):

self.c=c

defgetprice(self,price):

return

self.c.getprice(price)

if__name__=='

__main__':

strategy={}

strategy[0]=context(origin())

strategy[1]=context(vip())

strategy[2]=context(sale())

price=485s=2price_last=strategy[s].getprice(price)

print price_last

策略模式中,系統會根據不同的策略,返回不同的值,例如超市裡面,會有不同的計價方法,例如普通客戶會以原價來計價,vip

會打八折,活動**時滿

100減

20,這裡就有三種策略,在系統中,輸入原價和採取的策略方式,系統就會根據選擇的策略,計算消費者最終需要支付的金額。策略模式與工廠模式類似,例如上面的例子也可以用工廠模式來實現,就是新建三個類,每個類都有乙個計價的方法。而策略模式和工廠模式的區別是策略模式更

適用於策略不同的情景,也就是類中的方法不同,而工廠模式更適合類不同的情景。

單例模式

class

singleton(object):

def__new__(type, *args, **kwargs):

ifnot

'_the_instance

'in type.__dict__

: type._the_instance = object.__new__(type, *args, **kwargs)

return

type._the_instance

class

mysin(singleton):

b=0def__init__

(self):

print

self.b

ifnot self.b:self.b+=1

print

self.b

self.a=[1]

defchange(self):

c1=mysin()

c2=mysin()

print

c1.a

c1.change()

print c2.a

參考:

python學習 設計模式之 工廠模式

一 工廠模式運用場景 若需要將物件的建立和使用解耦,工廠方法也能派上用場。工廠方法可以在必要時建立新的物件,從而提高效能和記憶體使用率。二 工廠模式案例 import xml.etree.elementtree as etree import json class jsonconnector def...

學習python 單例設計模式

pyhton建立乙個物件的過程。單例設計模式的一種實現方式。當我們例項化乙個物件的時候,基本上可以分為如下步驟 呼叫 new cls 方法來建立乙個物件,然後找了乙個變數來接受 new 的返回值,這個返回值表示建立出來的物件的引用 呼叫 init 剛建立出來的物件的引用 方法,初始化成員變數。返回物...

python學習 設計模式之單例模式

一 什麼是單例模式 單例模式 singleton pattern 是一種常用的軟體設計模式,該模式的主要目的是確保某乙個類只有乙個例項存在。當你希望在整個系統中,某個類只能出現乙個例項時,單例物件就能派上用場。二 實現單例的方法 三 模組 python 模組在第一次匯入時,會生成 pyc 檔案,當第...