在设计大型和复杂的软件系统时,设计模式是解决常见问题的有效方法。本教程将深入探讨Python中的高级设计模式。

目录

单例模式

单例模式确保一个类只有一个实例,并提供一个全局访问点。

class Singleton:
    _instance = None

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

singleton = Singleton.getInstance()

工厂模式

工厂模式提供了一种创建对象的方法,而不必指定对象的具体类。

class Dog:
    pass

class Cat:
    pass

class AnimalFactory:
    @staticmethod
    def create_animal(animal_type):
        if animal_type == 'dog':
            return Dog()
        elif animal_type == 'cat':
            return Cat()

dog = AnimalFactory.create_animal('dog')

策略模式

策略模式允许在运行时选择算法的行为。

class SortingStrategy:
    def sort(self, items):
        pass

class BubbleSort(SortingStrategy):
    def sort(self, items):
        # 实现冒泡排序
        pass

class QuickSort(SortingStrategy):
    def sort(self, items):
        # 实现快速排序
        pass

def sort_items(items, strategy):
    strategy.sort(items)

装饰器模式

装饰器模式允许在不修改原有对象的情况下增加新的功能。

def debug(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with arguments {args} and keyword arguments {kwargs}")
        return func(*args, **kwargs)
    return wrapper

@debug
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

Python设计模式