Design patterns
1.Creational patterns
(1)工厂(factory)
封装对象的创建过程,可以不用暴露对象的具体细节
将对象实例化过程和客户端代码分离,使用户看到的代码简洁,灵活
(2)Singleton(单例)
确保一个类只有一个实例,可以避免资源冲突和浪费,方便集中管理
并提供全局访问点访问该实例,使其他对象可以访问该实例
2.Structural Patterns
(1)Decorator(装饰器)
本质是一个嵌套函数,传入的参数是类或函数
def our_decorator(func):
def function_wrapper(x):
print(‘Before calling ‘ + func.__name__)
func(x)
print(‘After calling ‘ + func.__name__)
return function_wrapper
def foo(x):
print(‘Hi, foo has been called with ‘ + str(x))
>>> foo(‘Hi’)
Hi, foo has been called with Hi
>>> foo = our_decorator(foo)
>>> foo(42)
'''输出'''
Before calling foo
Hi, foo has been called with 42
After calling foo
上面的our_decorator函数我们可以用装饰器(语法糖)封装起来
def our_decorator(func):
... As above …
@our_decorator
def foo(x):
print(‘Hi, foo has been called with ‘ + str(x))
(2)Adapter(适配器)
用于将一个接口转换成另一个接口,是不兼容的两个类能够协同工作
接口就是规定要程序做什么,但不在其中实现
(3)Facade(外观)
封装复杂接口和功能,提供简化接口,客户端可以用这个接口直接访问系统功能,无需了解底层系统的复杂性
3. Behavioral Patterns
(1)Iterator(迭代器)
一个具有状态的对象,在迭代过程中会记住它所在的位置;
__next__()方法:返回下一个迭代值,更新状态指向下一个值,迭代完成抛出StopIteration
__iter__()方法:返回整个地带其
comprehensions:允许我们在一行代码中转换或者过滤可迭代对象
input_strings = ['1', '5', '28', '131', '3’]
output_integers = []
for num in input_strings:
output_integers.append(int(num))
'''经过comprehensions后'''
input_strings = ['1', '5', '28', '131', ‘3’]
output_integers = [int(num) for num in input_strings]
Generators (生成器)
yield方法将一个值生成为生成器的下一个元素,并在生成器暂停执行时返回给调用者,在下一次调用时,可以从yield标记的暂停位置的元素继续生成
def firstn(n):
num = 0
while num < n:
yield num
num += 1
>>> gen = firstn(3)
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
File "python", line 1, in <module>
StopIteration
squares_list = [i**2 for i in firstn(6)]
print(squares_list)
>>>[0, 1, 4, 9, 16, 25]
注意Comprehensions和Generators不属于Patterns
(2)Strategy(策略模式)
可以封装算法,把每个算法变成独立的可以相互替换的对象,可以将算法块挪动填补,而不用修改其中的具体代码。
Architectual Patterns
体系结构模式是一种高级的抽象模式。
架构模式允许将系统分解成可以(在某种程度上)开发和独立维护的块。
这些模式支持大规模、长期的开发和维护。
大型系统很少符合单一的架构模式
Layered
将系统划分成多个层次,层与层之间用特定的接口进行通信
Data Flows
数据可以从一个模块流向另一个模块
Client - Server
服务器组件为一个或多个客户端提供一个功能或服务,这些客户端启动对此类服务的请求。
点对点应用程序(Peer to peer)——在具有同等状态的组件(对等体)之间划分的点对点应用程序任务。
代理(Broker)——负责协调多个分布式对象之间的通信的组件。
虚拟机(Virtual Machines)——将应用程序视为用特殊目的语言编写的程序。
Model - View - Control(MVC)
支持用户界面开发(数据的多个视图)。
模型——数据的一种模型或表示形式。为这些数据提供了一个接口。
视图——数据的表示。可以独立开发,但不应该包含任何复杂的逻辑。开发逻辑应该留在控制器或模型中。
控制器——接受输入,并将其转换为模型或视图的命令。