📜  Python设计模式(1)

📅  最后修改于: 2023-12-03 15:04:42.009000             🧑  作者: Mango

Python设计模式

Python设计模式是指在Python编程中使用的一种模式或模板,它们是不同问题的通用解决方案。这些模式提供了一种可重用的方法来解决常见的问题和任务,使程序更加健壮、可维护和可扩展。

创建型模式

创建型模式是专注于对象创建的模式。这些模式使得对象的创建和实例化更加灵活,而且有助于减少对象的数量。在Python中,最常见的创建型模式是:

工厂模式

工厂模式是一种创建型模式,它提供了一种创建对象的最佳方式。该模式实现了从父类向子类的对象实例化,而不是直接使用 new() 构造函数。

from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def num_wheels(self):
        pass

class Car(Vehicle):
    def num_wheels(self):
        return 4

class Motorcycle(Vehicle):
    def num_wheels(self):
        return 2

def get_vehicle(num_wheels):
    if num_wheels == 4:
        return Car()
    elif num_wheels == 2:
        return Motorcycle()
    else:
        return None
单例模式

单例模式用于创建一个类,该类在整个应用程序中只需要一个实例。这对于跨多个模块访问和共享共享资源非常有用。

class Singleton:
    __instance = None
    @staticmethod
    def getInstance():
        if Singleton.__instance == None:
            Singleton()
        return Singleton.__instance 
    def __init__(self):
        if Singleton.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            Singleton.__instance = self
建造者模式

建造者模式是一种对象创建模式,它允许使用相同的构造步骤来创建多个类型的对象。这使得建造者模式比其他创建型模式更加灵活。

class Director:
    def __init__(self, builder):
        self._builder = builder

    def construct_car(self):
        self._builder.new_car()
        self._builder.add_wheels()
        self._builder.add_engine()

class Builder:
    def new_car(self):
        self.car = Car()

    def add_wheels(self):
        pass

    def add_engine(self):
        pass

class CarBuilder(Builder):
    def add_wheels(self):
        self.car.wheels = 4

    def add_engine(self):
        self.car.engine = 'Gasoline'

class ElectricCarBuilder(Builder):
    def add_wheels(self):
        self.car.wheels = 4

    def add_engine(self):
        self.car.engine = 'Electric'
结构型模式

结构型模式是一种用于处理对象之间关系的模式,它涉及包括继承、合成和对象组合等关系。

适配器模式

适配器模式使得两个不兼容的接口得以兼容。Python中,最常见的适配器模式是

class Target:
    def request(self):
        return "Target: The default target's behavior."

class Adaptee:
    def specific_request(self):
        return ".eetpadA eht fo roivaheb laicepS"

class Adapter(Target):
    def __init__(self, adaptee):
        self._adaptee = adaptee

    def request(self):
        return f"Adapter: (TRANSLATED) {self._adaptee.specific_request()[::-1]}"

adaptee = Adaptee()
adapter = Adapter(adaptee)
adapter.request()
组合模式

组合模式使您能够将对象组合成更复杂的结构,比如树形结构。

class Component:
    def __init__(self, *args, **kwargs):
        pass
    def component_function(self):
        pass

class Leaf(Component):
    def __init__(self, *args, **kwargs):
        Component.__init__(self, *args, **kwargs)
        self.name = args[0]
    def component_function(self):
        return f"Leaf {self.name}\n"

class Composite(Component):
    def __init__(self, *args, **kwargs):
        Component.__init__(self, *args, **kwargs)
        self.name = args[0]
        self.children = []
    def append_child(self, child):
        self.children.append(child)
    def remove_child(self, child):
        self.children.remove(child)
    def component_function(self):
        string = f"Composite {self.name}\n"
        for child in self.children:
            string += child.component_function()
        return string

sub1 = Composite("SubComposite 1")
sub2 = Composite("SubComposite 2")
leaf1 = Leaf("Leaf 1")
leaf2 = Leaf("Leaf 2")

tree = Composite("RootComposite")
tree.append_child(sub1)
tree.append_child(sub2)
sub1.append_child(leaf1)
sub2.append_child(leaf2)

print(tree.component_function())
装饰器模式

装饰器模式是一种在运行时动态地向对象添加功能的方式,而不是通过继承创建一个新的子类。

def decorate(func):
    def new_function():
        print('Preparing to call function...')
        func()
        print('Done calling function.')
    return new_function

@decorate
def original():
    print('In original function')

original()
行为型模式

行为型模式是一种关注对象之间的协作方式的模式,与对象的结构或创建方式无关。

观察者模式

观察者模式是一种常见的行为型模式,用于在对象之间建立一对多的依赖关系。

class Subject:
    def __init__(self):
        self.observers = []
    def register_observer(self, observer):
        self.observers.append(observer)
    def remove_observer(self, observer):
        if observer in self.observers:
            self.observers.remove(observer)
    def notify_observers(self):
        for observer in self.observers:
            observer.update()

class Observer:
    def __init__(self):
        self.subject = None
    def update(self):
        pass

class ConcreteObserver(Observer):
    def update(self):
        print('ConcreteObserver received notification.')

subject = Subject()
observer = ConcreteObserver()
subject.register_observer(observer)
subject.notify_observers()
策略模式

策略模式是一种行为型模式,它允许您在运行时更改算法的行为。

class Strategy:
    def do_operation(self, num1, num2):
        pass

class OperationAdd(Strategy):
    def do_operation(self, num1, num2):
        return num1 + num2

class OperationSubtract(Strategy):
    def do_operation(self, num1, num2):
        return num1 - num2

class OperationMultiply(Strategy):
    def do_operation(self, num1, num2):
        return num1 * num2

class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def execute_strategy(self, num1, num2):
        return self.strategy.do_operation(num1, num2)

context = Context(OperationAdd())
print(context.execute_strategy(10, 5))
context = Context(OperationSubtract())
print(context.execute_strategy(10, 5))
context = Context(OperationMultiply())
print(context.execute_strategy(10, 5))
模板模式

模板模式是一种行为型模式,用于定义算法的基本骨架,而将某些步骤委托给子类完成。

class AbstractClass:
    def template_method(self):
        self.base_operation1()
        self.required_operation1()
        self.base_operation2()
        self.hook1()
        self.required_operation2()
        self.base_operation3()
        self.hook2()

    def base_operation1(self):
        print('AbstractClass.base_operation1()')

    def base_operation2(self):
        print('AbstractClass.base_operation2()')

    def base_operation3(self):
        print('AbstractClass.base_operation3()')

    def hook1(self):
        pass

    def hook2(self):
        pass

    def required_operation1(self):
        pass

    def required_operation2(self):
        pass

class ConcreteClass1(AbstractClass):
    def required_operation1(self):
        print('ConcreteClass1.required_operation1()')

    def required_operation2(self):
        print('ConcreteClass1.required_operation2()')

class ConcreteClass2(AbstractClass):
    def required_operation1(self):
        print('ConcreteClass2.required_operation1()')

    def required_operation2(self):
        print('ConcreteClass2.required_operation2()')

template = ConcreteClass1()
template.template_method()

template = ConcreteClass2()
template.template_method()