python class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class MyClass(metaclass=Singleton): pass python class Shape: def draw(self): pass class Circle(Shape): def draw(self): print("Drawing a circle") class Rectangle(Shape): def draw(self): print("Drawing a rectangle") class ShapeFactory: def create_shape(self, shape_type): if shape_type == "circle": return Circle() elif shape_type == "rectangle": return Rectangle() else: raise ValueError("Invalid shape type") shape_factory = ShapeFactory() circle = shape_factory.create_shape("circle") circle.draw() # Output: Drawing a circle python from abc import ABC, abstractmethod from typing import List, Any class Observable: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(observer) def notify_observers(self, data): for observer in self._observers: observer.update(data) class Observer(ABC): @abstractmethod def update(self, data: Any): pass class TemperatureSensor(Observable): def set_temperature(self, temperature): self.notify_observers(temperature) class Display(Observer): def update(self, data): print("Temperature:", data) sensor = TemperatureSensor() display = Display() sensor.add_observer(display) sensor.set_temperature(25) # Output: Temperature: 25


上一篇:
下一篇:
切换中文