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

python设计模式1:创建型模式

2015-10-07 12:34 561 查看
1.原型模式

如果想根据现有的对象复制出新的对象并进行修改,可以考虑“原型模式”,而无需知道任何创建细节。(有点像写轮眼...你不需要知道它)

import copy

class Point:
__slots__ = ("x","y")

def __init__(self,x,y):
self.x = x
self.y = y

point1 = Point(1,2)
point2 = copy.deepcopy(point1)
print(point2.x)
point2.x = 3
print(point2.x)    #answer:1,3


2.单例模式

如果在整个程序运行过程中,某个类只应该有一个实例,那么可通过单例模式来保证。有一种实现单例模式比较简单的办法是:创建模块时,把全局状态放在私有变量中,并提供用于访问此变量的公开函数。

举个例子,如果我们要实现一个功能,这个功能可以返回含有货币汇率的字典键值对。那么有两种办法可以实现:

(1)每次调用时先创建字典,然后读取文件,从字典取出值。

(2)加一个判断的flag,保证在同一个单例下,第一次把字典创建好,以后直接从字典里取值。

明显(2)好于(1)

import urllib

_URL = "http://www.banlofcanada.ca/stats/assets/csv/fx-seven-day.csv"

def get(refresh=False):
if refresh:
get.rates = {}
if get.rates:
return get.rates
with urllib.request.urlopen(_URL) as file:
for line in file:
line = line.rstrip().decode("utf-8")
if not line or line.startswith(("#","Date")):
continue
name,currency,*rest = re.split(r"\s*,\s*",line)
key = "{} ({})".format(name,currency)
try:
get.rates[key] = float(rest[-1])
except ValueError as err:
print("error {}: {}".format(err,line))
return get.rates
get.rates={}


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