个人技术分享

目录

一、工厂模式(Factory Pattern)

 二、单例模式(Singleton Pattern)

三、观察者模式(Observer Pattern) 


一、工厂模式(Factory Pattern)

        工厂模式(Factory Pattern):工厂模式是一种创建型模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

Python 例子:

class Creator:
    def factory_method(self):
        raise NotImplementedError('Subclasses must implement this method!')
 
class ConcreteProductA(Creator):
    def factory_method(self):
        return ProductA()
 
class ConcreteProductB(Creator):
    def factory_method(self):
        return ProductB()
 
class ProductA:
    pass
 
class ProductB:
    pass
 
def client_code(creator):
    product = creator.factory_method()
    product.do_something()
 
# 使用
creator_a = ConcreteProductA()
client_code(creator_a)
 
creator_b = ConcreteProductB()
client_code(creator_b)

 二、单例模式(Singleton Pattern)

        单例模式(Singleton Pattern):单例模式是一种创建型模式,它确保一个类只有一个实例,并提供一个全局访问点。

Python 例子:

class Singleton:
    _instance = None
 
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
 
singleton_instance = Singleton()
another_instance = Singleton()
 
# singleton_instance 和 another_instance 是同一个实例
print(singleton_instance is another_instance)  # 输出: True

三、观察者模式(Observer Pattern) 

        观察者模式(Observer Pattern):观察者模式是一种行为型模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象状态发生改变时,它的所有依赖者(观察者)都会收到通知并自动更新。

Python 例子:

class Subject:
    def __init__(self):
        self._observers = []
 
    def attach(self, observer):
        self._observers.append(observer)
 
    def notify(self):
        for observer in self._observers:
            observer.update()
 
class Observer:
    def update(self):
        raise NotImplementedError('Subclasses must implement this method!')
 
class ConcreteObserver(Observer):
    def update(self):
        print('Observer received an update!')
 
# 使用
subject = Subject()
observer = ConcreteObserver()
subject.attach(observer)
subject.notify()  # 输出: Observer received an update!

代码之美,在于创造无限可能!