Python设计模式(一)

一、简单工厂模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-26 20:24
# @Author  : Maple
# @File    : 01-简单工厂模式.py

from abc import ABC,abstractmethod

# 1. 简单入门
class Dog:

    def speak(self):
        return "I am Dog"

class Cat:

    def speak(self):
        return "I am cat"


class MyFactory1:

    @staticmethod
    def getAnimal(name):
        if name == "dog":
            return Dog()
        elif name == "cat":
            return Cat()
        else:
          raise ValueError("请输入正确的类型")

# 2. 进阶1:增加一个注册类的功能
class MyFactory2:

    cls_dict = {}

    @classmethod
    def register_cls(cls,name,clss):
        cls.cls_dict[name] = clss

    @classmethod
    def get_obj(cls,name):
        kls = cls.cls_dict.get(name)
        if kls is None:
            raise ValueError(f"Plugin with name {name} not registered.")
        else:
            return kls()


class Person:
    pass

class Student:
    pass


# 3. 进阶2:利用抽象类
# 抽象工厂类
class UIFactory:
    def create_button(self):
        raise NotImplementedError

    def create_textbox(self):
        raise NotImplementedError


# 具体工厂类:Windows
class WindowsUIFactory(UIFactory):
    def create_button(self):
        return WindowsButton()

    def create_textbox(self):
        return WindowsTextbox()


# 具体工厂类:MacOS
class MacOSUIFactory(UIFactory):
    def create_button(self):
        return MacOSButton()

    def create_textbox(self):
        return MacOSTextbox()


# 抽象产品类:Button
class Button:
    def render(self):
        raise NotImplementedError


# 抽象产品类:Textbox
class Textbox:
    def render(self):
        raise NotImplementedError


# 具体产品类:Windows Button
class WindowsButton(Button):
    def render(self):
        return "Rendering a Windows style button"


# 具体产品类:Windows Textbox
class WindowsTextbox(Textbox):
    def render(self):
        return "Rendering a Windows style textbox"


# 具体产品类:MacOS Button
class MacOSButton(Button):
    def render(self):
        return "Rendering a MacOS style button"


# 具体产品类:MacOS Textbox
class MacOSTextbox(Textbox):
    def render(self):
        return "Rendering a MacOS style textbox"


# Usage
def client_code(factory: UIFactory):
    button = factory.create_button()
    textbox = factory.create_textbox()
    print(button.render())
    print(textbox.render())


# 4. 进阶3:要创建的类带初始化参数,并且不同的子类参数不一样
class Character:
    def __init__(self, name, level):
        self.name = name
        self.level = level

    def __str__(self):
        return f"{self.name}, Level {self.level}"

class Warrior(Character):
    def __init__(self, name, level, weapon):
        super().__init__(name, level)
        self.weapon = weapon

    def __str__(self):
        return f"{super().__str__()}, armed with {self.weapon}"

class Mage(Character):
    def __init__(self, name, level, element):
        super().__init__(name, level)
        self.element = element

    def __str__(self):
        return f"{super().__str__()}, wielding {self.element} magic"

class CharacterFactory:
    @staticmethod
    def create_character(type, name, level, **kwargs):
        if type == "warrior":
            return Warrior(name, level, kwargs.get('weapon', 'sword'))
        elif type == "mage":
            return Mage(name, level, kwargs.get('element', 'fire'))
        else:
            raise ValueError("Unknown character type")



if __name__ == '__main__':

    print('*******1. 简单入门测试*****************')
    # 1. 简单入门测试
    dog = MyFactory1.getAnimal("dog")
    print(dog.speak())

    cat = MyFactory1.getAnimal("cat")
    print(cat.speak())

    print('*******2. 进阶测试-1*******************')

    # 2. 进阶测试-1
    MyFactory2.register_cls('Person',Person)
    MyFactory2.register_cls('Student',Student)

    p = MyFactory2.get_obj('Person')
    print(p)

    s = MyFactory2.get_obj('Student')
    print(s)

    # 3. 进阶测试-2
    print('*******3. 进阶测试-2*******************')
    # Depending on the OS environment, we might choose a different factory
    current_os = 'Windows'  # This could be determined by some runtime check
    if current_os == 'Windows':
        factory = WindowsUIFactory()
    elif current_os == 'MacOS':
        factory = MacOSUIFactory()

    """
       Rendering a Windows style button
       Rendering a Windows style textbox
    """
    client_code(factory)

    # 4. 进阶测试-3
    print('*******4. 进阶测试-3*******************')
    warrior = CharacterFactory.create_character("warrior", "Aragorn", 5, weapon="long sword")
    mage = CharacterFactory.create_character("mage", "Gandalf", 10, element="lightning")

    print(warrior)  # Output: Aragorn, Level 5, armed with long sword
    print(mage)  # Output: Gandalf, Level 10, wielding lightning magic

二、代理模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-26 22:03
# @Author  : Maple
# @File    : 02-代理模式.py



"""
代理设计模式是一种结构型设计模式,允许对象在访问另一个对象时提供一个代替品或占位符。
这样可以控制对这个对象的访问,添加额外的功能或者管理生命周期等。在Python中实现代理模式通常涉及定义一个代理类,
该类包含对实际对象的引用,并通过重写方法以添加额外的行为。
"""


"""
例子1:简单的保护代理
在这个简单的例子中,代理类控制对另一个类的访问,只有当满足特定条件时才允许访问
"""

class SensitiveInfo:
    def display_info(self):
        return "Sensitive Information: Only authorized users can see this."

class ProtectedProxy:
    def __init__(self, user):
        self.user = user
        self._sensitive_info = SensitiveInfo()

    def display_info(self):
        if self.user == "authorized_user":
            return self._sensitive_info.display_info()
        else:
            return "Access Denied: You are not authorized to access this information."



"""
例子2:虚拟代理
这个例子中,代理类延迟实际对象的创建,只有在真正需要时才创建,用于节省资源或延迟计算开销。
"""
class HeavyObject:
    def __init__(self):
        import time
        time.sleep(2)  # Simulating a heavy creation task
        print("Heavy Object Created")

    def process(self):
        return "Processing complete."

class VirtualProxy:
    def __init__(self):
        self._object = None

    def process(self):
        # 当真正需要调用HeavyObject的process方法时,才会去创建HeavyObject实例对象
        # 虚拟代理是一种懒加载(Lazy Loading)机制
        if self._object is None:
            self._object = HeavyObject()
        return self._object.process()




"""
例子3:智能引用代理
在更复杂的情况下,代理类可以添加对对象的智能引用管理,比如记录对象操作的次数或实现引用计数。
"""

class DataStore:
    def load_data(self):
        return "Data loaded"

    def save_data(self, data):
        print(f"Data saved: {data}")

class LoggingProxy:
    def __init__(self, target):
        self._target = target
        self._load_count = 0
        self._save_count = 0

    def load_data(self):
        self._load_count += 1
        print(f"Data load operation count: {self._load_count}")
        return self._target.load_data()

    def save_data(self, data):
        self._save_count += 1
        print(f"Data save operation count: {self._save_count}")
        return self._target.save_data(data)

"""
例子4:远程代理
远程代理用于控制对远程对象(比如网络上的服务)的访问。远程代理作为本地对象的代表
,通过网络与远程对象进行交互
"""

import requests

class RemoteServiceProxy:
    def __init__(self, service_url):
        self.service_url = service_url

    def fetch_data(self):
        response = requests.get(self.service_url)
        if response.status_code == 200:
            return response.json()
        else:
            return None

"""
例子 5:缓存代理
缓存代理用于管理对资源密集型对象的访问,它保存结果并在后续请求中重用,以提高效率和速度。
"""

class DataHeavyService:
    def complex_query(self, parameters):
        # Simulate a complex query
        return f"Results for {parameters}"

class CacheProxy:
    def __init__(self, target):
        self.target = target
        self.cache = {}

    def complex_query(self, parameters):
        if parameters not in self.cache:
            self.cache[parameters] = self.target.complex_query(parameters)
        return self.cache[parameters]



if __name__ == '__main__':

    print("*************案例1:简单的保护代理************")

    proxy = ProtectedProxy("authorized_user")
    print(proxy.display_info())  # Output: Sensitive Information: Only authorized users can see this.

    proxy_unauthorized = ProtectedProxy("unauthorized_user")
    print(proxy_unauthorized.display_info())  # Output: Access Denied: You are not authorized to access this information.

    print("*************案例2:虚拟代理************")

    proxy = VirtualProxy()
    print(proxy.process())  # Output: Heavy Object Created\nProcessing complete.

    print("*************案例3:智能引用代理************")
    data_store = DataStore()
    proxy = LoggingProxy(data_store)
    print(proxy.load_data())  # Output: Data load operation count: 1\nData loaded
    proxy.save_data("Some data")  # Output: Data save operation count: 1\nData saved: Some data

    print("*************案例4:远程代理************")
    proxy = RemoteServiceProxy("https://www.baidu.com")
    data = proxy.fetch_data()
    print(data)  # Outputs the data fetched from the remote service

    print("*************案例5:缓存代理************")
    service = DataHeavyService()
    proxy = CacheProxy(service)
    print(proxy.complex_query("param1"))  # Slow the first time
    print(proxy.complex_query("param1"))  # Fast, uses cache

三、单例模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-27 7:05
# @Author  : Maple
# @File    : 03-单例模式.py

"""
单例模式是一种常见的设计模式,用于确保一个类有且只有一个实例
并提供一个全局访问点来访问这个实例。单例模式通常用于全局状态或共享资源的管理,如配置管理器、连接池等。

"""

"""
案例1:基础单例模式
这是实现单例模式的最基础形式,使用了一个类变量来存储该类的唯一实例。
"""
class Singleton:
    _instance = None

    @staticmethod
    def get_instance():
        if Singleton._instance is None:
            Singleton._instance = Singleton()
        return Singleton._instance

    def __init__(self):
        if Singleton._instance is not None:
            raise Exception("This class is a singleton!")
        else:
            Singleton._instance = self

    def release_instance(self):
        Singleton._instance = None

"""
案例2:线程安全的单例模式
在多线程环境中,确保单例实例的创建过程是线程安全的,这通常通过使用线程锁来实现。
"""

from threading import Lock, Thread

class ThreadSafeSingleton:
    _instance = None
    _lock = Lock()  # 创建一个锁

    @staticmethod
    def getInstance():
        if ThreadSafeSingleton._instance is None:
            with ThreadSafeSingleton._lock:
                if ThreadSafeSingleton._instance is None:
                    ThreadSafeSingleton._instance = ThreadSafeSingleton()
        return ThreadSafeSingleton._instance

    def __init__(self):
        if ThreadSafeSingleton._instance is not None:
            raise Exception("This class is a singleton!")
        else:
            ThreadSafeSingleton._instance = self


"""
这个例子展示了如何使用Python装饰器来创建一个单例
这种方法将单例的逻辑封装在装饰器中,使得实现单例模式变得更加优雅。
"""
def singleton(cls):
    instance = None
    def get_instance(*args, **kwargs):
        nonlocal instance
        if instance is None:
            instance = cls(*args, **kwargs)
        return instance
    return get_instance

@singleton
class DecoratedSingleton:
    def __init__(self, value):
        self.value = value




if __name__ == '__main__':

    print('*******案例1: 基础入门************')

    s0 = Singleton()
    s1 = Singleton.get_instance()
    s2 = Singleton.get_instance()
    print(s1 == s2)  # Output: True
    print(s0 == s1)  # Output: True

    # 此时Singleton._instance已经不是None了,所以会raise Exception("This class is a singleton!")
    try:
        s3 = Singleton()
    except Exception as e:
        print("This class is a singleton!")

    # 销毁实例
    s0.release_instance()

    # 重新创建实例
    s4 = Singleton()
    print(s4) # <__main__.Singleton object at 0x000002216E63FE80>

    s5 = Singleton.get_instance()
    print(s4 == s5) # True


    print('*******案例2: 线程安全的单例模式************')

    def test_singleton():
        singleton = ThreadSafeSingleton.getInstance()
        print(id(singleton))


    threads = [Thread(target=test_singleton) for _ in range(5)]
    """
     2566637996160
     2566637996160
     2566637996160
     2566637996160
     2566637996160
    """
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    print('*******案例3: 使用装饰器的单例模式************')
    s1 = DecoratedSingleton(10)
    # 第二次传入的初始化参数将被忽略
    s2 = DecoratedSingleton(20)
    print(s1.value)  # Output: 10
    print(s2.value)  # Output: 10【注意这里仍然是10】
    print(s1 is s2)  # Output: True

四、观察者模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-27 7:17
# @Author  : Maple
# @File    : 04-观察者模式.py

"""

观察者模式是一种设计模式,其中一个对象(称为“主题”)维护一组依赖于它的对象(称为“观察者”)
,并在主题的状态发生改变时自动通知它们。这种模式在实现事件处理系统、数据同步等功能时非常有用。
"""

"""
例子1:基本的观察者模式
这个例子中,我们创建了一个简单的新闻发布系统,新闻机构可以订阅新闻服务并在有新新闻时收到通知。 
"""

class NewsPublisher:
    def __init__(self):
        self.subscribers = []
        self.latest_news = None

    def add_subscriber(self, subscriber):
        self.subscribers.append(subscriber)

    def remove_subscriber(self, subscriber):
        self.subscribers.remove(subscriber)

    def notify_subscribers(self):
        for subscriber in self.subscribers:
            subscriber.update(self.latest_news)

    def add_news(self, news):
        self.latest_news = news
        self.notify_subscribers()

class NewsAgency:
    def update(self, news):
        print(f"News Agency received news: {news}")

"""
例子2:使用回调函数的观察者模式
这个例子中,我们创建了一个简单的新闻发布系统,新闻机构可以订阅新闻服务并在有新新闻时收到通知。 
"""

class EventManager:
    def __init__(self):
        self.listeners = {}

    def subscribe(self, event_type, listener):
        if event_type not in self.listeners:
            self.listeners[event_type] = []
        self.listeners[event_type].append(listener)

    def unsubscribe(self, event_type, listener):
        if event_type in self.listeners:
            self.listeners[event_type].remove(listener)

    def notify(self, event_type, data):
        if event_type in self.listeners:
            for listener in self.listeners[event_type]:
                listener(data) # listener是一个回调函数,当触发notify的时候,会调用该方法



def handle_temperature_change(data):
    print(f"Temperature Alert: {data} degrees")


def handle_pressure_change(data):
    print(f"Pressure Alert: {data} hPa")

"""
案例3:复杂的多主题观察者模式
这个例子中,我们创建了一个可以处理多种事件和多个主题的系统,使得观察者可以订阅多个主题的多种事件。
"""

class MultiSubjectManager:
    def __init__(self):
        self.subjects = {}

    def register_subject(self, subject_name):
        if subject_name not in self.subjects:
            self.subjects[subject_name] = {}

    def subscribe(self, subject_name, event_type, observer):
        """
        :param subject_name: 主题
        :param event_type: 事件
        :param observer: 观察着
        :return:
        """
        if subject_name in self.subjects:
            if event_type not in self.subjects[subject_name]:
                self.subjects[subject_name][event_type] = []
            self.subjects[subject_name][event_type].append(observer)

    def unsubscribe(self, subject_name, event_type, observer):
        if subject_name in self.subjects and event_type in self.subjects[subject_name]:
            self.subjects[subject_name][event_type].remove(observer)

    def notify(self, subject_name, event_type, data):
        if subject_name in self.subjects and event_type in self.subjects[subject_name]:
            for observer in self.subjects[subject_name][event_type]:
                observer(data)


def stock_event_handler(data):
    print(f"Stock Event: {data}")

def weather_event_handler(data):
    print(f"Weather Update: {data}")



if __name__ == '__main__':

    print('*******案例1:基本的观察者模式 **********')
    publisher = NewsPublisher()
    agency1 = NewsAgency()
    agency2 = NewsAgency()

    publisher.add_subscriber(agency1)
    publisher.add_subscriber(agency2)
    publisher.add_news("New economic policies released.")

    """
    Output:
    News Agency received news: New economic policies released.
    News Agency received news: New economic policies released.
    """

    print('*******案例2:使用回调函数的观察者模式 **********')
    manager = EventManager()
    manager.subscribe("temperature", handle_temperature_change)
    manager.subscribe("pressure", handle_pressure_change)

    """
    Temperature Alert: 26 degrees
    Pressure Alert: 1013 hPa
    """
    manager.notify("temperature", 26)
    manager.notify("pressure", 1013)

    print('*******案例3:复杂的多主题观察者模式 **********')
    manager = MultiSubjectManager()
    manager.register_subject("stock")
    manager.register_subject("weather")

    manager.subscribe("stock", "price_change", stock_event_handler)
    manager.subscribe("weather", "temperature_change", weather_event_handler)

    manager.notify("stock", "price_change", "AAPL stock price dropped 2%")
    manager.notify("weather", "temperature_change", "Temperature rose to 75°F")

五、建造者模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-27 14:28
# @Author  : Maple
# @File    : 05-建造者模式.py



"""
例子 1:简单的餐饮包建造者
这个例子中,我们将创建一个简单的快餐餐包建造者,可以组合不同类型的主菜、小吃和饮料。

"""
class Meal:
    def __init__(self):
        self.items = []

    def add_item(self, item):
        self.items.append(item)

    def get_cost(self):
        return sum(item.price for item in self.items)

    def show_items(self):
        for item in self.items:
            print(f"Item: {item.name}, Packing: {item.packing()}, Price: {item.price}")


# 商品抽象类,包含三个属性: 名称, 打包方式, 价格
class Item:
    def name(self):
        raise NotImplementedError

    def packing(self):
        raise NotImplementedError

    def price(self):
        raise NotImplementedError

# 商品打包方式的具体实现类-1
class Wrapper:
    def pack(self):
        return "Wrapper"

# 商品打包方式的具体实现类-1
class Bottle:
    def pack(self):
        return "Bottle"

# Burger和Drink代表两类产品
class Burger(Item):
    def packing(self):
        return Wrapper().pack()

class Drink(Item):
    def packing(self):
        return Bottle().pack()

# VegBurger是具体的产品--源头是继承item
# 因此会具备item的三个属性: 名称, 打包方式-才Burger中继承而来(Wrapper), 价格
class VegBurger(Burger):
    @property
    def price(self):
        return 25

    @property
    def name(self):
        return "Veg Burger"

# 同上
class ChickenBurger(Burger):
    @property
    def price(self):
        return 50

    @property
    def name(self):
        return "Chicken Burger"

# 同上
class Coke(Drink):
    @property
    def price(self):
        return 15

    @property
    def name(self):
        return "Coke"

# 同上
class Pepsi(Drink):
    @property
    def price(self):
        return 10

    @property
    def name(self):
        return "Pepsi"


class MealBuilder:
    def prepare_veg_meal(self):
        meal = Meal()
        meal.add_item(VegBurger())
        meal.add_item(Coke())
        return meal

    def prepare_non_veg_meal(self):
        meal = Meal()
        meal.add_item(ChickenBurger())
        meal.add_item(Pepsi())
        return meal


"""
案例2:复杂的汽车建造者
在这个例子中,我们将创建一个更复杂的汽车建造者,可以选择不同的汽车型号、引擎、内饰等。
"""

class Car:
    def __init__(self):
        self.features = {}

    def add_feature(self, key, value):
        self.features[key] = value

    def show_details(self):
        for feature, value in self.features.items():
            print(f"{feature}: {value}")

class CarBuilder:
    def __init__(self):
        self.car = Car()

    def add_model(self, model):
        self.car.add_feature("model", model)
        return self

    def add_engine(self, engine):
        self.car.add_feature("engine", engine)
        return self

    def add_interior(self, interior):
        self.car.add_feature("interior", interior)
        return self

    def build(self):
        return self.car

"""
案例3:软件配置建造者
这个例子展示了如何使用建造者模式来构建软件配置文件。这种方法可以动态地创建和管理软件配置,尤其适用于配置项繁多且复杂的场景。

使用场景
这种建造者模式的实现特别适合于需要动态创建复杂配置的应用,例如:
云基础设施配置
多环境部署(开发、测试、生产)
服务端应用配置
这个模式提高了代码的可读性和可维护性,尤其在配置参数众多且频繁变动的系统中,可以显著简化配置管理工作。
"""

class Configuration:
    def __init__(self):
        self.parameters = {}

    def set_parameter(self, key, value):
        self.parameters[key] = value

    def show_configuration(self):
        for param, value in self.parameters.items():
            print(f"{param}: {value}")

class ConfigurationBuilder:
    def __init__(self):
        self.configuration = Configuration()

    def set_database(self, db_name):
        self.configuration.set_parameter("database", db_name)
        return self

    def set_server_ip(self, ip):
        self.configuration.set_parameter("server_ip", ip)
        return self

    def set_max_connections(self, max_connections):
        self.configuration.set_parameter("max_connections", max_connections)
        return self

    def set_timeout(self, timeout):
        self.configuration.set_parameter("timeout", timeout)
        return self

    def build(self):
        return self.configuration






if __name__ == '__main__':


    print('********案例1:餐饮包建造者 *****************')
    meal_builder = MealBuilder()
    veg_meal = meal_builder.prepare_veg_meal()
    veg_meal.show_items()
    """
      Item: Veg Burger, Packing: Wrapper, Price: 25
      Item: Coke, Packing: Bottle, Price: 15
    """
    print(f"Total Cost: {veg_meal.get_cost()}") # Total Cost: 40

    non_veg_meal = meal_builder.prepare_non_veg_meal()
    non_veg_meal.show_items()
    """
     Item: Chicken Burger, Packing: Wrapper, Price: 50
     Item: Pepsi, Packing: Bottle, Price: 10
    """
    print(f"Total Cost: {non_veg_meal.get_cost()}") # Total Cost: 60


    print('********案例2:复杂的汽车建造者 *****************')
    builder = CarBuilder()
    car = (builder.add_model("Sports Car")
           .add_engine("V8 Engine")
           .add_interior("Leather Interior")
           .build())
    """
    model: Sports Car
    engine: V8 Engine
    interior: Leather Interior
    """
    car.show_details()

    print('********案例3:软件配置建造者 *****************')
    config_builder = ConfigurationBuilder()
    configuration = (config_builder.set_database("MySQL")
                     .set_server_ip("192.168.1.100")
                     .set_max_connections(100)
                     .set_timeout(30)
                     .build())

    """
    database: MySQL
    server_ip: 192.168.1.100
    max_connections: 100
    timeout: 30
    """
    configuration.show_configuration()

六、适配器模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-27 15:03
# @Author  : Maple
# @File    : 06-适配器模式.py

"""
适配器模式是一种结构型设计模式,它允许接口不兼容的对象能够合作。
适配器模式通常用于确保由于接口不兼容而无法一起工作的类可以一起工作。
它通过在一个独立的类中封装现有的类,这个独立的类提供了符合目标接口的行为。
"""

"""
例子 1:电源适配器
展示如何使用适配器模式将一个类的接口转换为另一个接口
假设我们有一个只能接受特定电压的设备,而电源插座的输出电压与设备不匹配,我们需要一个适配器来调整电压
"""

# 目标接口
class EuropeanSocketInterface:
    def voltage(self):
        pass

# 适配者 --电源插座: 230V
class Socket(EuropeanSocketInterface):
    def voltage(self):
        return 230

# 客户端 - 用户设备: 只能使用120V的插座
class Radio:
    def __init__(self, power_source):
        self.power_source = power_source

    def plug_in(self):
        if self.power_source.voltage() == 120:
            print("Radio playing music!")
        else:
            print("Can't use this socket!")

# 适配器
class SocketAdapter(EuropeanSocketInterface):
    def __init__(self, socket):
        self.socket = socket

    #  将电源插座的电压从230V调整到120V
    def voltage(self):
        return self.socket.voltage() // 1.916


"""
案例2:遗留代码与现代系统的集成
假设我们有一个遗留系统的类,它返回用户数据的格式与新系统不兼容。新系统需要JSON格式,但遗留系统提供的是字典列表。
"""

import json

# 遗留系统
class OldSystem:
    def get_user_data(self):
        return [{"name": "John", "age": 30}, {"name": "Alice", "age": 25}]

# 新系统的期望接口
class NewSystem:
    # 新系统期望处理的是JSON格式的数据
    def process_user_data(self, user_data):
        print(f"Processing data: {user_data}")

# 适配器
class Adapter:
    def __init__(self, old_system):
        self.old_system = old_system

    def get_user_data(self):
        old_data = self.old_system.get_user_data()
        # 旧系统返回的数据转换成Json格式
        return json.dumps(old_data)

"""
案例3:多个数据库适配
在这个更复杂的例子中,假设我们的应用需要与多种数据库交互,但每种数据库的接口不同。我们可以使用适配器模式统一这些接口。
"""
# 目标接口
class DatabaseInterface:
    def connect(self):
        pass

    def execute(self):
        pass

# 适配者:MySQL数据库
class MySQLDatabase:
    def connect_mysql(self):
        print("Connecting to MySQL database.")

    def execute_mysql(self, query):
        print(f"Executing '{query}' on MySQL database.")

# 适配者:SQLite数据库
class SQLiteDatabase:
    def connect_sqlite(self):
        print("Connecting to SQLite database.")

    def execute_sqlite(self, query):
        print(f"Executing '{query}' on SQLite database.")

# 适配器
class MySQLAdapter(DatabaseInterface):
    def __init__(self, mysql_db):
        self.mysql_db = mysql_db

    def connect(self):
        self.mysql_db.connect_mysql()

    def execute(self, query):
        self.mysql_db.execute_mysql(query)

class SQLiteAdapter(DatabaseInterface):
    def __init__(self, sqlite_db):
        self.sqlite_db = sqlite_db

    def connect(self):
        self.sqlite_db.connect_sqlite()

    def execute(self, query):
        self.sqlite_db.execute_sqlite(query)

"""
案例4:多源输入适配器
在从多个数据源接收数据时,适配器可以帮助统一和标准化数据格式。
"""
class SensorA:
    def get_temperature(self):
        return 22.5  # Celsius

class SensorB:
    def read_temp(self):
        return "Temperature is 295.65K"  # Kelvin

class SensorAdapter:
    def __init__(self, sensor):
        self.sensor = sensor

    def get_temperature_celsius(self):
        if isinstance(self.sensor, SensorA):
            return self.sensor.get_temperature()
        elif isinstance(self.sensor, SensorB):
            kelvin = float(self.sensor.read_temp().split()[-1][:-1])
            return kelvin - 273.15  # Convert Kelvin to Celsius





if __name__ == '__main__':


    print('******案例1:电源适配器 **************')
    socket = Socket()
    adapter = SocketAdapter(socket)
    radio = Radio(adapter)
    radio.plug_in()  # Output: Radio playing music!

    print('******案例2:遗留代码与现代系统的集成**************')
    old_system = OldSystem()
    adapter = Adapter(old_system)
    new_system = NewSystem()
    # adapter.get_user_data()返回的是Json格式的数据,满足新系统的期望
    new_system.process_user_data(adapter.get_user_data())  # 正确处理JSON数据

    print('******案例3:多个数据库适配**************')
    mysql_db = MySQLDatabase()
    sqlite_db = SQLiteDatabase()

    mysql_adapter = MySQLAdapter(mysql_db)
    sqlite_adapter = SQLiteAdapter(sqlite_db)

    mysql_adapter.connect()
    mysql_adapter.execute("SELECT * FROM users")

    sqlite_adapter.connect()
    sqlite_adapter.execute("SELECT * FROM settings")

    print('******案例4:多源输入适配器**************')
    sensor_a = SensorA()
    sensor_b = SensorB()

    adapter_a = SensorAdapter(sensor_a)
    adapter_b = SensorAdapter(sensor_b)

    print(f"Temperature from Sensor A: {adapter_a.get_temperature_celsius()}°C")
    print(f"Temperature from Sensor B: {adapter_b.get_temperature_celsius()}°C")

七、桥接模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-28 8:52
# @Author  : Maple
# @File    : 07-桥接模式.py


"""
桥接模式是一种结构型设计模式,用于将抽象部分与其实现部分分离,使它们可以独立地变化
这种模式非常有用,特别是在系统中某些结构可能有多种实现方式时
通过桥接模式,可以组合使用不同的抽象和实现,而不必在抽象层面固定住一个特定的实现
"""


"""
案例1:简单的消息发送系统
在这个简单的例子中,我们将创建一个消息发送系统,其中消息发送的方式(如通过电子邮件、短信等)和消息的优先级处理是分离的。
"""

# Implementor
class MessageSender:
    def send(self, message):
        raise NotImplementedError

# Concrete Implementors
class EmailSender(MessageSender):
    def send(self, message):
        print(f"Email: {message}")

class SMSSender(MessageSender):
    def send(self, message):
        print(f"SMS: {message}")

# Abstraction
class Message:
    def __init__(self, sender):
        self.sender = sender

    def send(self, message):
        self.sender.send(message)

# Refined Abstraction
class UrgentMessage(Message):
    def send(self, message):
        super().send(f"[Urgent] {message}")


"""
案例2:多设备图形渲染系统
在这个例子中,我们将创建一个图形渲染系统
可以在不同的设备上渲染图形(如在窗口或者文件中),而渲染的具体图形(如圆形或矩形)由另一层抽象处理。
"""

# Implementor(实现者)
"""
Renderer是一个接口,定义了渲染操作的基本方法,如render_circle 和 render_square。这是桥接模式中的“实现者”层。
"""
class Renderer:
    def render_circle(self, radius):
        raise NotImplementedError

    def render_square(self, dimension):
        raise NotImplementedError


# Concrete Implementors(具体实现者)
# 渲染技术:矢量渲染
class VectorRenderer(Renderer):
    def render_circle(self, radius):
        print(f"Drawing a circle of radius {radius} with VectorRenderer")

    def render_square(self, dimension):
        print(f"Drawing a square of size {dimension} with VectorRenderer")

#渲染技术:像素(栅格)方式渲染图形
class RasterRenderer(Renderer):
    def render_circle(self, radius):
        print(f"Drawing pixels for a circle of radius {radius} with RasterRenderer")

    def render_square(self, dimension):
        print(f"Drawing pixels for a square of size {dimension} with RasterRenderer")


# Abstraction(抽象层)
"""
Shape 是一个抽象类,它持有一个 Renderer 类型的引用。Shape定义了一个基本的 draw 方法
该方法在具体的图形类中被实现。这是桥接模式中的“抽象”层。
"""
class Shape:
    def __init__(self, renderer):
        self.renderer = renderer

    def draw(self):
        pass


# Refined Abstraction(精化抽象)
"""
Circle 和 Square 是从Shape派生的具体类。它们分别代表圆形和方形,实现了 draw 方法来调用相应的渲染技术
"""
class Circle(Shape):
    def __init__(self, renderer, radius):
        super().__init__(renderer)
        self.radius = radius

    def draw(self):
        self.renderer.render_circle(self.radius)


class Square(Shape):
    def __init__(self, renderer, dimension):
        super().__init__(renderer)
        self.dimension = dimension

    def draw(self):
        self.renderer.render_square(self.dimension)


"""
案例3:多平台窗口系统
这个例子展示了如何创建一个可以在多个操作系统上运行的窗口系统,使用不同的平台API渲染窗口和不同的控件风格
"""
# Implementor
class WindowImplementor:
    def draw_window(self, title):
        raise NotImplementedError

    def draw_button(self, title):
        raise NotImplementedError

# Concrete Implementors
"""
不同系统平台的窗口
"""
class WindowsImplementor(WindowImplementor):
    def draw_window(self, title):
        print(f"Windows window: {title}")

    def draw_button(self, title):
        print(f"Windows button: {title}")

class LinuxImplementor(WindowImplementor):
    def draw_window(self, title):
        print(f"Linux window: {title}")

    def draw_button(self, title):
        print(f"Linux button: {title}")

# Abstraction
class Window:
    def __init__(self, window_imp):
        self.window_imp = window_imp

    def draw(self):
        raise NotImplementedError

    def draw_button(self):
        raise NotImplementedError

# Refined Abstraction
"""
不同风格的窗口
"""
class IconWindow(Window):
    def __init__(self, window_imp):
        super().__init__(window_imp)

    def draw(self, title):
        print("Drawing icon window...")
        self.window_imp.draw_window(title)

    def draw_button(self, button_title):
        self.window_imp.draw_button(button_title)

class TranslucentWindow(Window):
    def __init__(self, window_imp):
        super().__init__(window_imp)

    def draw(self, title):
        print("Drawing translucent window...")
        self.window_imp.draw_window(title)

    def draw_button(self, button_title):
        self.window_imp.draw_button(button_title)






if __name__ == '__main__':

    print('*******案例1:简单的消息发送系统***************')
    email_sender = EmailSender()
    sms_sender = SMSSender()

    message = Message(email_sender)
    message.send("Hello, Bridge Pattern!")

    urgent_message = UrgentMessage(sms_sender)
    urgent_message.send("Please call me ASAP!")

    print('*******案例2:多设备图形渲染系统**************')
    vector_renderer = VectorRenderer()
    raster_renderer = RasterRenderer()

    circle1 = Circle(vector_renderer, 3)
    circle2 = Circle(raster_renderer,3)
    square1 = Square(vector_renderer, 10)
    square2 = Square(raster_renderer, 10)
    """
    Drawing a circle of radius 3 with VectorRenderer
    Drawing pixels for a circle of radius 3 with RasterRenderer
    Drawing a square of size 10 with VectorRenderer
    Drawing pixels for a square of size 10 with RasterRenderer

    """
    circle1.draw()
    circle2.draw()
    square1.draw()
    square2.draw()

    print('*******案例3:多平台窗口系统**************')
    windows_imp = WindowsImplementor()
    linux_imp = LinuxImplementor()

    icon_window = IconWindow(windows_imp)
    translucent_window = TranslucentWindow(linux_imp)

    icon_window.draw("My Application")
    icon_window.draw_button("OK")
    translucent_window.draw("My Application")
    translucent_window.draw_button("Cancel")
    """
    Drawing icon window...
    Windows window: My Application
    Windows button: OK
    Drawing translucent window...
    Linux window: My Application
    Linux button: Cancel
    """

八、组合模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024-04-28 9:29
# @Author  : Maple
# @File    : 08-组合模式.py


"""
组合模式是一种结构型设计模式,用于以树形结构表示部分以及整体层次结构, 使得客户统一的方式处理个别对象以及对象的组合
这种模式非常有用于处理具有递归组成的数据结构。下面是几个示例,展示了如何从简单到复杂应用组合模式。
"""

"""
案例1:文件系统
在这个例子中,我们使用组合模式来管理文件系统中的文件和文件夹。文件和文件夹可以被统一看待,从而简化了对它们的操作。
"""

class FileSystemElement:
    def show_details(self):
        raise NotImplementedError

class File(FileSystemElement):
    def __init__(self, name, size):
        self.name = name
        self.size = size

    def show_details(self):
        print(f"File: {self.name}, Size: {self.size}KB")

class Directory(FileSystemElement):
    def __init__(self, name):
        self.name = name
        self.children = []

    def add(self, element):
        self.children.append(element)

    def remove(self, element):
        self.children.remove(element)

    def show_details(self):
        print(f"Directory: {self.name}")
        for child in self.children:
            child.show_details()


"""
案例2:图形对象
这个例子展示了如何使用组合模式来管理图形对象,例如圆形、矩形等,以及它们的组合。
"""

class Graphic:
    def draw(self):
        raise NotImplementedError

class Circle(Graphic):
    def draw(self):
        print("Drawing a circle")

class Rectangle(Graphic):
    def draw(self):
        print("Drawing a rectangle")

class CompositeGraphic(Graphic):
    def __init__(self):
        self.graphics = []

    def add(self, graphic):
        self.graphics.append(graphic)

    def remove(self, graphic):
        self.graphics.remove(graphic)

    def draw(self):
        for graphic in self.graphics:
            graphic.draw()
class Graphic:
    def draw(self):
        raise NotImplementedError

class Circle(Graphic):
    def draw(self):
        print("Drawing a circle")

class Rectangle(Graphic):
    def draw(self):
        print("Drawing a rectangle")

class CompositeGraphic(Graphic):
    def __init__(self):
        self.graphics = []

    def add(self, graphic):
        self.graphics.append(graphic)

    def remove(self, graphic):
        self.graphics.remove(graphic)

    def draw(self):
        for graphic in self.graphics:
            graphic.draw()

class Graphic:
    def draw(self):
        raise NotImplementedError

class Circle(Graphic):
    def draw(self):
        print("Drawing a circle")

class Rectangle(Graphic):
    def draw(self):
        print("Drawing a rectangle")

class CompositeGraphic(Graphic):
    def __init__(self):
        self.graphics = []

    def add(self, graphic):
        self.graphics.append(graphic)

    def remove(self, graphic):
        self.graphics.remove(graphic)

    def draw(self):
        for graphic in self.graphics:
            graphic.draw()


"""
案例3:公司结构
这个例子使用组合模式来描述一个公司的组织结构,包括部门和员工。
"""

class OrganizationComponent:
    def __init__(self, name):
        self.name = name

    def add(self, component):
        raise NotImplementedError

    def remove(self, component):
        raise NotImplementedError

    def get_name(self):
        return self.name

    def display_details(self):
        raise NotImplementedError

class Department(OrganizationComponent):
    def __init__(self, name):
        super().__init__(name)
        self.components = []

    def add(self, component):
        self.components.append(component)

    def remove(self, component):
        self.components.remove(component)

    def display_details(self):
        print(f"Department: {self.name}")
        for component in self.components:
            component.display_details()

class Employee(OrganizationComponent):
    def add(self, component):
        print("Leaf can't add component")

    def remove(self, component):
        print("Leaf can't remove component")

    def display_details(self):
        print(f"Employee: {self.name}")







if __name__ == '__main__':

    print('******案例1:文件系统******************')
    root = Directory("root")
    child1 = Directory("child1")
    child2 = Directory("child2")
    file1 = File("file1", 100)
    file2 = File("file2", 200)

    root.add(child1)
    root.add(child2)
    child1.add(file1)
    child2.add(file2)

    """
    Directory: root
    Directory: child1
    File: file1, Size: 100KB
    Directory: child2
    File: file2, Size: 200KB
    """

    root.show_details()

    print('******案例2:图形对象******************')
    circle = Circle()
    rectangle = Rectangle()
    composite = CompositeGraphic()
    composite.add(circle)
    composite.add(rectangle)

    """
    Drawing a circle
    Drawing a rectangle
    """
    composite.draw()

    print('******案例3:图形对象******************')
    dev_dept = Department("Development")
    hr_dept = Department("Human Resources")

    dev_emp1 = Employee("Alice")
    dev_emp2 = Employee("Bob")
    hr_emp1 = Employee("Charlie")

    dev_dept.add(dev_emp1)
    dev_dept.add(dev_emp2)
    hr_dept.add(hr_emp1)

    company = Department("Company")
    company.add(dev_dept)
    company.add(hr_dept)

    """
    Department: Company
    Department: Development
    Employee: Alice
    Employee: Bob
    Department: Human Resources
    Employee: Charlie
    """
    company.display_details()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/580976.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

python 调试 c++源码

1. gdb常用调试命令概览和说明 2. 编译c库设置Debug模式 cmake设置debug 在CMake中设置debug模式通常意味着启用调试信息和优化。以下是一个简单的CMakeLists.txt文件示例&#xff0c;展示了如何设置项目以便在Debug模式下构建&#xff1a; cmake_minimum_required(VERSION 3…

深度学习| 注意力机制

注意力机制 为什么需要注意力机制Seq2Seq问题Transfomer Attention注意力机制分类软硬注意力注意力域 为什么需要注意力机制 这个可以从NLP的Seq2Seq问题来慢慢理解。 Seq2Seq问题 Seq2Seq&#xff08;Sequence to Sequence&#xff09;&#xff1a;早期很多模型中&#xff…

Linux逻辑方式合并物理磁盘

在日常生活中&#xff0c;我们总是遇到一个文件太大&#xff0c;以至于我们的两个磁盘都装不下&#xff0c;这时我们就需要将两块物理磁盘逻辑化的连接在一起&#xff0c;把物理磁盘使用逻辑化的方法合并在一起&#xff0c;形成卷组&#xff0c;使得磁盘空间可以公用&#xff1…

Leetcode—1672. 最富有客户的资产总量【简单】

2024每日刷题&#xff08;120&#xff09; Leetcode—1672. 最富有客户的资产总量 实现代码 class Solution { public:int maximumWealth(vector<vector<int>>& accounts) {int ans 0;for(vector<vector<int>>::iterator it accounts.begin();…

西门子PLC常见疑难解答在这都能找到(含PLC无线通讯实例)

问&#xff1a;在WINCC中可以创建多少个消息类型&#xff1f; 答&#xff1a;WINCC中最多可以创建16个消息类型。 问&#xff1a;博途WINCC与经典版WINCC兼容嘛&#xff1f; 答&#xff1a;经典wincc和博图wincc Professional版本都不兼容 不能安装到一起的哦&#xff01; …

探讨mfc100u.dll丢失的解决方法,修复mfc100u.dll有效方法解析

mfc100u.dll丢失是一个比较常见的情况&#xff0c;由于你电脑的各种操作&#xff0c;是有可能引起dll文件的缺失的&#xff0c;而mfc100u.dll就是其中的一个重要的dll文件&#xff0c;它的确实严重的话是会导致程序打不开&#xff0c;系统错误的。今天我们就来给大家科普一下mf…

命令执行漏洞【2】vulhub远程命令执行漏洞复现

1.vulhub安装启动靶场环境 &#xff08;1&#xff09;s2-061开启靶场 &#xff08;2&#xff09;s2-059开启靶场 2.漏洞复现 &#xff08;1&#xff09;s2-061漏洞复现 github获取漏洞利用工具 开始利用 &#xff08;2&#xff09;s2-059漏洞复现 在linux特有临时目录/tmp下…

968.监控二叉树 树上最小支配集

法一: 动态规划 一个被支配的节点只会有三种状态 1.它本身有摄像头 2.他没有摄像头, 但是它的父节点有摄像头 3.他没有摄像头, 但是它的子节点有摄像头 我们 dfs(node,state) 记录在node节点时(以node为根的子树),状态为state下的所有最小摄像头 // 本身有摄像头就看左右孩子…

投影连接Samba服务

目录 0.创建【Samba服务】 1.下载・安装一个能连接【Samba服务】的播放器 2.配置语言 3.配置服务器连接 0.创建【Samba服务】 Linux&#xff08;Ubuntu&#xff09;中创建【samba】服务&#xff0c;用于和Windows系统之间共享文件_ubuntu samba-CSDN博客 1.下载・安装一…

《深入理解mybatis原理》 MyBatis的架构设计以及实例分析

《深入理解mybatis原理》 MyBatis的架构设计以及实例分析 MyBatis是目前非常流行的ORM框架&#xff0c;它的功能很强大&#xff0c;然而其实现却比较简单、优雅。本文主要讲述MyBatis的架构设计思路&#xff0c;并且讨论MyBatis的几个核心部件&#xff0c;然后结合一个select查…

Matlab进阶绘图第51期—带填充等高线的三维特征渲染散点图

带填充等高线的三维特征渲染散点图是填充等高线图与特征渲染三维散点图的组合。 其中&#xff0c;填充等高线图与特征渲染的三维散点图的颜色用于表示同一个特征。 由于填充等高线图无遮挡但不直观&#xff0c;特征渲染的三维散点图直观但有遮挡&#xff0c;而将二者组合&…

【C++杂货铺】二叉搜索树

目录 &#x1f308;前言&#x1f308; &#x1f4c1; 二叉搜索树的概念 &#x1f4c1; 二叉搜索树的操作 &#x1f4c2; 二叉搜索树的查找 &#x1f4c2; 二叉搜索树的插入 &#x1f4c2; 二叉搜书树的删除 &#x1f4c1; 二叉搜索树的应用 &#x1f4c1; 二叉搜索树的…

vue3 h5模板

vue3的h5模板 基于vue3tsvantrem的h5模板 觉得帮到你了就给个start

【win10移动热点,提示正在获取ip地址...】

检查 Wired AutoConfig/ WLAN AutoConfig 服务运行 电脑→管理→服务和应用程序→服务&#xff1a;AutoConfig 有线网络无线网卡 1.开启wifi热点&#xff0c;自动生成“本地连接*10”&#xff1b; 2.配置Wired LAN网络共享 仅无线网卡 1. 开启wifi热点&#xff0c;自动生…

自学Python爬虫js逆向(二)chrome浏览器开发者工具的使用

js逆向中很多工作需要使用浏览器中的开发者工具&#xff0c;所以这里以chrome为例&#xff0c;先把开发者工具的使用总结一下&#xff0c;后面用到的时候可以回来查询。 Google Chrome浏览器的开发者工具是前端开发者的利器&#xff0c;它不仅提供了丰富的功能用于开发、调试和…

电动公共交通车充电站设置储能电站方案

相比于传统燃油公交车&#xff0c;电动公交车以电代油&#xff0c;具有零排放、低噪音、低能耗等优势。随着电池、车载电机等相关技术的不断发展&#xff0c;电动公交车在国内乃至全世界范围内逐步推广应用。动力电池是电动公交车的重要部件之一&#xff0c;其寿命及性能影响着…

解密推理部署工程师的必备技能,面试题库分析

推理部署工程师面试题库 1. 描述一下SM的结构&#xff1f; 英伟达 GPU 架构&#xff1a;* 计算核心&#xff1a;INT32、FP32、FP64 CUDA 核心&#xff0c;Tensor 核心&#xff0c;超低延迟负载/存储。* 调度和存储器&#xff1a;Warp 调度器注册文件&#xff0c;共享存储器&am…

逻辑回归模型与GBDT+LR——特征工程模型化的开端

随着信息技术和互联网的发展&#xff0c; 我们已经步入了一个信息过载的时代&#xff0c;这个时代&#xff0c;无论是信息消费者还是信息生产者都遇到了很大的挑战&#xff1a; 信息消费者&#xff1a;如何从大量的信息中找到自己感兴趣的信息&#xff1f;信息生产者&#xff…

主题乐园私域精细化运营

主题乐园私域精细化运营是指在细分用户群体的基础上&#xff0c;通过个性化、精准的运营方式&#xff0c;为用户提供定制化服务和体验。以下是一些常见的主题乐园私域精细化运营玩法&#xff1a; 会员制度和会员专属服务&#xff1a;建立完善的会员制度&#xff0c;为会员提供专…

碳实践 | 一文读懂LCA产品生命周期环境影响评价

一、产品生命周期评价定义 生命周期评价&#xff1a;生命周期评价&#xff08;Life Cycle Assessment&#xff0c;简称LCA&#xff09;是一种量化评价方法。它涵盖了产品的整个生命周期——从自然资源开采到原材料加工、产品制造、分销、使用&#xff0c;直至最终废弃处置或回…
最新文章