Python的23种设计模式
设计模式是一种解决特定问题的经验总结,它可以提供一种可重用的解决方案,能够在不同的场景中使用。Python是一种功能强大的编程语言,它提供了丰富的库和工具,可以方便地实现各种设计模式。本文将介绍Python中的23种常见设计模式,并提供一些代码示例来说明它们的用法。
创建型模式
1. 工厂模式
工厂模式是一种创建对象的方式,它将对象的创建过程封装在一个工厂类中,通过调用工厂类的方法来创建对象。这样可以隐藏具体对象的创建细节,使客户端代码更加简洁。
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
factory = AnimalFactory()
dog = factory.create_animal("dog")
print(dog.speak()) # 输出: Woof!
2. 单例模式
单例模式是一种保证类只能有一个实例的设计模式。它使用一个私有的静态变量来保存唯一的实例,并提供一个公共的静态方法来获取这个实例。
class Singleton:
_instance = None
@staticmethod
def get_instance():
if not Singleton._instance:
Singleton._instance = Singleton()
return Singleton._instance
# 获取单例实例
singleton = Singleton.get_instance()
3. 原型模式
原型模式是一种通过复制已有对象来创建新对象的设计模式。它适用于创建成本较高的对象,通过复制已有对象可以提高对象的创建效率。
import copy
class Prototype:
def clone(self):
return copy.deepcopy(self)
# 创建原型对象
prototype = Prototype()
# 复制原型对象
clone = prototype.clone()
4. 建造者模式
建造者模式是一种将复杂对象的构建与它的表示分离的设计模式。它通过指挥者类来控制建造过程,在创建对象时可以灵活地使用不同的建造者,以达到不同的表示。
class Product:
def __init__(self):
self.parts = []
def add_part(self, part):
self.parts.append(part)
class Builder:
def build_part1(self):
pass
def build_part2(self):
pass
def get_product(self):
pass
class Director:
def __init__(self, builder):
self.builder = builder
def construct(self):
self.builder.build_part1()
self.builder.build_part2()
# 创建建造者和指挥者对象
builder = Builder()
director = Director(builder)
# 构建产品
director.construct()
product = builder.get_product()
结构型模式
1. 适配器模式
适配器模式是一种将不兼容的接口转换为可兼容的接口的设计模式。它通过创建一个适配器类来将不兼容的接口包装成兼容的接口,以方便客户端使用。
class Adaptee:
def specific_request(self):
return "Specific request"
class Target:
def request(self):
return "Target request"
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee
def request(self):
return self.adaptee.specific_request()
# 创建适配器对象
adaptee = Adaptee()
adapter = Adapter(adaptee)
# 使用适配器对象
print(adapter.request()) # 输出: Specific request
2. 桥接模式
桥接模式是一种将抽象部分与实现部分分离的设计模式。它使用一个桥接接口来连接抽象部分和实现部分,使它们可以独立地变化。
class Implementor:
def implementation(self):
pass
class Abstraction:
def __init__(self, implementor):
self.implementor = implementor
def operation(self):
self.implementor.implementation()
#