Python設(shè)計(jì)模式怎么實(shí)現(xiàn)

小億
83
2024-05-11 12:08:00

Python設(shè)計(jì)模式是通過(guò)編寫(xiě)符合特定設(shè)計(jì)模式規(guī)范的代碼來(lái)實(shí)現(xiàn)的。以下是一些常見(jiàn)設(shè)計(jì)模式的實(shí)現(xiàn)方式:

  1. 單例模式:確保一個(gè)類(lèi)只有一個(gè)實(shí)例,并提供全局訪(fǎng)問(wèn)點(diǎn)。實(shí)現(xiàn)方式包括使用模塊化、使用裝飾器或者使用元類(lèi)等方式。
class Singleton:
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

# 使用單例模式創(chuàng)建實(shí)例
instance1 = Singleton()
instance2 = Singleton()

print(instance1 is instance2)  # True
  1. 工廠(chǎng)模式:定義一個(gè)創(chuàng)建對(duì)象的接口,讓子類(lèi)決定實(shí)例化哪個(gè)類(lèi)。實(shí)現(xiàn)方式包括簡(jiǎn)單工廠(chǎng)模式、工廠(chǎng)方法模式和抽象工廠(chǎng)模式。
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    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()

# 使用工廠(chǎng)模式創(chuàng)建實(shí)例
factory = AnimalFactory()
dog = factory.create_animal("dog")
cat = factory.create_animal("cat")

print(dog.speak())  # "Woof!"
print(cat.speak())  # "Meow!"
  1. 觀察者模式:定義一個(gè)一對(duì)多的依賴(lài)關(guān)系,當(dāng)一個(gè)對(duì)象的狀態(tài)發(fā)生改變時(shí),所有依賴(lài)于它的對(duì)象都會(huì)收到通知并自動(dòng)更新。實(shí)現(xiàn)方式包括使用內(nèi)置的Observable類(lèi)和Observer接口。
from abc import ABC, abstractmethod
from typing import List

class Observer(ABC):
    @abstractmethod
    def update(self, message: str):
        pass

class Subject:
    _observers: List[Observer] = []

    def add_observer(self, observer: Observer):
        self._observers.append(observer)

    def remove_observer(self, observer: Observer):
        self._observers.remove(observer)

    def notify_observers(self, message: str):
        for observer in self._observers:
            observer.update(message)

# 使用觀察者模式
class ConcreteObserver(Observer):
    def update(self, message: str):
        print(f"Received message: {message}")

subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()

subject.add_observer(observer1)
subject.add_observer(observer2)

subject.notify_observers("Hello, world!")

以上是三種常見(jiàn)設(shè)計(jì)模式的實(shí)現(xiàn)方式,你可以根據(jù)需要選擇合適的設(shè)計(jì)模式來(lái)實(shí)現(xiàn)你的程序。

0