Python学习笔记-设计模式篇
单例模式
# 方法 1: 使用类变量
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
# 测试单例模式
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # 输出: True
# 方法 2: 使用类装饰器
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Singleton:
pass
# 测试单例模式
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # 输出: True
# 方法 3: 使用元类
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
pass
# 测试单例模式
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # 输出: True
# 方法 4: 使用模块
# singleton.py
class Singleton:
def __init__(self):
self.value = None
singleton_instance = Singleton()
# main.py
import singleton
s1 = singleton.singleton_instance
s2 = singleton.singleton_instance
print(s1 is s2) # 输出: True
工厂方法模式
class Product:
def operation(self):
pass
class ConcreteProductA(Product):
def operation(self):
return "ConcreteProductA"
class ConcreteProductB(Product):
def operation(self):
return "ConcreteProductB"
class Creator:
def factory_method(self):
pass
def some_operation(self):
product = self.factory_method()
return f"Creator: The same creator's code has just worked with {product.operation()}"
class ConcreteCreatorA(Creator):
def factory_method(self):
return ConcreteProductA()
class ConcreteCreatorB(Creator):
def factory_method(self):
return ConcreteProductB()
creator_a = ConcreteCreatorA()
print(creator_a.some_operation())
creator_b = ConcreteCreatorB()
print(creator_b.some_operation())
抽象工厂模式
class AbstractFactory:
def create_product_a(self):
pass
def create_product_b(self):
pass
class ConcreteFactory1(AbstractFactory):
def create_product_a(self):
return ProductA1()
def create_product_b(self):
return ProductB1()
class ConcreteFactory2(AbstractFactory):
def create_product_a(self):
return ProductA2()
def create_product_b(self):
return ProductB2()
class AbstractProductA:
pass
class ProductA1(AbstractProductA):
pass
class ProductA2(AbstractProductA):
pass
class AbstractProductB:
pass
class ProductB1(AbstractProductB):
pass
class ProductB2(AbstractProductB):
pass
factory1 = ConcreteFactory1()
product_a1 = factory1.create_product_a()
product_b1 = factory1.create_product_b()
factory2 = ConcreteFactory2()
product_a2 = factory2.create_product_a()
product_b2 = factory2.create_product_b()
建造者模式
class Product:
def __init__(self):
self.parts = []
def add(self, part):
self.parts.append(part)
def show(self):
print(", ".join(self.parts))
class Builder:
def build_part_a(self):
pass
def build_part_b(self):
pass
def get_result(self):
pass
class ConcreteBuilder(Builder):
def __init__(self):
self.product = Product()
def build_part_a(self):
self.product.add("PartA")
def build_part_b(self):
self.product.add("PartB")
def get_result(self):
return self.product
class Director:
def construct(self, builder):
builder.build_part_a()
builder.build_part_b()
builder = ConcreteBuilder()
director = Director()
director.construct(builder)
product = builder.get_result()
product.show()
适配器模式
class Target:
def request(self):
return "Target: The default target's behavior."
class Adaptee:
def specific_request(self):
return ".eetpadA eht fo roivaheb laicepS"
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee
def request(self):
return f"Adapter: (TRANSLATED) {self.adaptee.specific_request()[::-1]}"
adaptee = Adaptee()
adapter = Adapter(adaptee)
print(adapter.request())
装饰器模式
class Component:
def operation(self):
pass
class ConcreteComponent(Component):
def operation(self):
return "ConcreteComponent"
class Decorator(Component):
def __init__(self, component):
self._component = component
def operation(self):
return self._component.operation()
class ConcreteDecoratorA(Decorator):
def operation(self):
return f"ConcreteDecoratorA({super().operation()})"
class ConcreteDecoratorB(Decorator):
def operation(self):
return f"ConcreteDecoratorB({super().operation()})"
component = ConcreteComponent()
decorator1 = ConcreteDecoratorA(component)
decorator2 = ConcreteDecoratorB(decorator1)
print(decorator2.operation())
观察者模式
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self):
for observer in self._observers:
observer.update(self)
class ConcreteSubject(Subject):
def __init__(self, state=0):
super().__init__()
self._state = state
@property
def state(self):
return self._state
@state.setter
def state(self, state):
self._state = state
self.notify()
class Observer:
def update(self, subject):
pass
class ConcreteObserver(Observer):
def update(self, subject):
print(f"Observer: Reacted to the event with state {subject.state}")
subject = ConcreteSubject()
observer = ConcreteObserver()
subject.attach(observer)
subject.state = 10
subject.state = 20
策略模式
class Strategy:
def do_algorithm(self, data):
pass
class ConcreteStrategyA(Strategy):
def do_algorithm(self, data):
return sorted(data)
class ConcreteStrategyB(Strategy):
def do_algorithm(self, data):
return sorted(data, reverse=True)
class Context:
def __init__(self, strategy):
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy):
self._strategy = strategy
def do_some_business_logic(self):
print("Context: Sorting data using the strategy (not sure how it'll do it)")
result = self._strategy.do_algorithm(["a", "b", "c", "d", "e"])
print(",".join(result))
context = Context(ConcreteStrategyA())
context.do_some_business_logic()
context.strategy = ConcreteStrategyB()
context.do_some_business_logic()
作者:wanghongwei
版权声明:本作品遵循<CC BY-NC-ND 4.0>版权协议,商业转载请联系作者获得授权,非商业转载请附上原文出处链接及本声明。