结构型模式
Structural Pattern
适配器模式
Adapter Pattern
适配器模式(Adapter Pattern):用于将一个类的接口转换成客户端期望的另一种接口。 该模式可让原本由于接口不兼容而不能一起工作的类能协同工作。 如,定义了一个英文翻译类,现需适配成中文翻译类,那么就可以使用适配器模式,在构造方法中构造英文类,再去实现中文方法
class EnglishSpeaker:
def say_hello(self):
print("Hello!")
class ChineseTranslator:
def __init__(self, english_speaker):
self.english_speaker = english_speaker
def speak_chinese(self):
print("你好!")
def translate(self):
self.speak_chinese() # "你好!"
self.english_speaker.say_hello() # "Hello!"
english_speaker = EnglishSpeaker()
chinese_translator = ChineseTranslator(english_speaker)
chinese_translator.translate() # 你好! Hello!
桥模式
Bridge Pattern
桥接模式(Bridge Pattern):将抽象部分和实现部分分离开,以便它们可以独立地变化。 例如,在游戏中有多种武器和角色,我们可以使用桥接模式将武器和角色分离开来,从而可自由地组合它们。
class Weapon:
def __init__(self, name):
self.name = name
class Sword(Weapon):
def attack(self):
print(f"{self.name} is attacking with sword!")
class Bow(Weapon):
def attack(self):
print(f"{self.name} is attacking with bow!")
class Character:
def __init__(self, name, weapon):
self.name = name
self.weapon = weapon
def attack(self):
self.weapon.attack()
class Warrior(Character):
pass
class Mage(Character):
pass
sword = Sword("Excalibur")
bow = Bow("Robin Hood's Bow")
warrior = Warrior("Arthur", sword)
mage = Mage("Merlin", bow)
warrior.attack() # Arthur is attacking with sword!
mage.attack() # Merlin is attacking with bow!
组合模式
Composite Pattern
组合模式(Composite Pattern): 将对象组合成树形结构以表示“整体-部分”层次结构。 如,在一个文件系统中,一个文件夹可以包含多个文件和子文件夹,可用组合模式来表示这个文件系统的结构。
class File:
def __init__(self, name):
self.name = name
def display(self, indent=''):
print(f"{indent}- {self.name}")
class Folder:
def __init__(self, name):
self.name = name
self.children = []
def add(self, child):
self.children.append(child)
def remove(self, child):
self.children.remove(child)
def display(self, indent=''):
print(f"{indent}+ {self.name}")
for child in self.children:
child.display(indent + ' ')
folder1 = Folder("Folder 1")
folder2 = Folder("Folder 2")
file1 = File("File 1")
file2 = File("File 2")
file3 = File("File 3")
folder1.add(file1)
folder1.add(folder2)
folder2.add(file2)
folder2.add(file3)
folder1.display()
'''
+ Folder 1
- File 1
+ Folder 2
- File 2
- File 3
'''
装饰器模式
Decorator Pattern
装饰器模式(Decorator Pattern): 用于动态地给一个对象添加一些新功能,同时不影响对象。 如,一个文本编辑器中,可以来给文本添粗、斜体等样式。
def decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@decorator
def some_function():
print("Function called")
some_function()
'''
Before function call
Function called
After function call
'''
外观模式
Facade Pattern
提供一个简单的接口,用于访问底层复杂系统的一些功能。相当于向上屏蔽。
class SubsystemA:
def operation_a(self):
pass
class SubsystemB:
def operation_b(self):
pass
class Facade:
def __init__(self):
self._subsystem_a = SubsystemA()
self._subsystem_b = SubsystemB()
def operation(self):
self._subsystem_a.operation_a()
self._subsystem_b.operation_b()
facade = Facade()
facade.operation()
亨元模式
Flyweight Pattern
允许将对象共享以节省内存和提高性能。Python 中,可使用缓存实现享元模式。
class Flyweight:
def __init__(self, shared_state):
self._shared_state = shared_state
def operation(self, unique_state):
s = f"shared ({self._shared_state}) and unique ({unique_state})"
print(s)
class FlyweightFactory:
_flyweights = {}
def get_flyweight(self, shared_state):
if shared_state not in self._flyweights:
self._flyweights[shared_state] = Flyweight(
shared_state)
return self._flyweights[shared_state]
factory = FlyweightFactory()
flyweight1 = factory.get_flyweight("state1")
flyweight2 = factory.get_flyweight("state1")
flyweight3 = factory.get_flyweight("state2")
flyweight4 = factory.get_flyweight("state2")
flyweight1.operation("unique1")
flyweight2.operation("unique2")
flyweight3.operation("unique3")
flyweight4.operation("unique4")
"""
shared (state1) and unique (unique1)
shared (state1) and unique (unique2)
shared (state2) and unique (unique3)
shared (state2) and unique (unique4)
"""
代理模式
Proxy Pattern
允许你提供一个代理对象作为另一个对象的接口。控制着对原始对象的访问,并允许创建一些附加行为,例如记录请求日志、缓存数据等。 Subject 是抽象类或接口,定义了 request() 方法的基本契约。RealSubject 实现了 Subject 接口,并实现了具体的 request() 方法。 Proxy 也实现了 Subject 接口,并包含一个 RealSubject 对象的引用。在执行请求之前,Proxy 首先检查用户的访问权限, 然后将请求转发给 RealSubject。通过使用 Proxy 对象,我们可以附加一些额外的功能,例如记录请求日志或缓存数据,而不改变 RealSubject 的代码。
class Subject:
def request(self):
pass
class RealSubject(Subject):
def request(self):
print("RealSubject: Handling request.")
class Proxy(Subject):
def __init__(self, real_subject: RealSubject):
self._real_subject = real_subject
def request(self):
if self.check_access():
self._real_subject.request()
def check_access(self):
print("Checking access prior to executing the request.")
return True
real_subject = RealSubject()
proxy = Proxy(real_subject)
proxy.request()
# "Checking access prior to executing the request."