匠心精神 - 良心品质腾讯认可的专业机构-IT人的高薪实战学院

咨询电话:4000806560

Python 设计模式实战:20 种强大的编程思想

Python 设计模式实战:20 种强大的编程思想

设计模式是软件开发中的最佳实践,它们是一组可复用的解决问题的解决方案,能够优化代码的结构,使代码更加可读、可维护、可扩展。本文将介绍 20 种 Python 设计模式并提供实战示例。

1. 单例模式

单例模式保证一个类只有一个实例,并提供了全局访问点。这种模式常用于控制资源并避免多个对象的副作用。

示例代码:

```python
class Singleton:
    __instance = None
    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance

s1 = Singleton()
s2 = Singleton()
print(s1)
print(s2)
```

输出:

```
<__main__.Singleton object at 0x102436080>
<__main__.Singleton object at 0x102436080>
```

2. 工厂模式

工厂模式定义一个创建对象的接口,但是让子类决定实例化哪个类。这种模式常用于解耦,使得代码更加灵活。

示例代码:

```python
class Vehicle:
    def move(self):
        pass
    
class Car(Vehicle):
    def move(self):
        print('Driving')

class Boat(Vehicle):
    def move(self):
        print('Sailing')

class VehicleFactory:
    def get_vehicle(self, vehicle_type):
        if vehicle_type == 'car':
            return Car()
        elif vehicle_type == 'boat':
            return Boat()

factory = VehicleFactory()
vehicle = factory.get_vehicle('car')
vehicle.move()
```

输出:

```
Driving
```

3. 抽象工厂模式

抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要指定具体类。

示例代码:

```python
class Vegetarian:
    def __init__(self):
        self.name = 'Vegetarian'

class Chicken:
    def __init__(self):
        self.name = 'Chicken'

class Pesto:
    def __init__(self):
        self.name = 'Pesto'

class Bolognese:
    def __init__(self):
        self.name = 'Bolognese'

class ItalianFoodFactory:
    def get_pasta(self):
        return Bolognese()

    def get_salad(self):
        return Pesto()

class AmericanFoodFactory:
    def get_pasta(self):
        return Chicken()

    def get_salad(self):
        return Vegetarian()

class FoodFactoryProducer:
    def get_factory(self, factory_type):
        if factory_type == 'italian':
            return ItalianFoodFactory()
        elif factory_type == 'american':
            return AmericanFoodFactory()

producer = FoodFactoryProducer()
factory = producer.get_factory('italian')
pasta = factory.get_pasta()
salad = factory.get_salad()
print(pasta.name)
print(salad.name)
```

输出:

```
Bolognese
Pesto
```

4. 建造者模式

建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

示例代码:

```python
class Pizza:
    def __init__(self):
        self.parts = []

    def add_part(self, part):
        self.parts.append(part)

    def __str__(self):
        return ', '.join(self.parts)

class PizzaBuilder:
    def __init__(self):
        self.pizza = Pizza()

    def add_cheese(self):
        self.pizza.add_part('cheese')

    def add_toppings(self, toppings):
        for topping in toppings:
            self.pizza.add_part(topping)

    def make_pizza(self):
        return self.pizza

builder = PizzaBuilder()
builder.add_cheese()
builder.add_toppings(['mushrooms', 'onions'])
pizza = builder.make_pizza()
print(pizza)
```

输出:

```
cheese, mushrooms, onions
```

5. 原型模式

原型模式通过克隆现有对象来创建新的对象。这种模式常用于资源密集型对象的创建,因为克隆较原始对象的操作可以节省时间和资源。

示例代码:

```python
import copy

class Prototype:
    def __init__(self):
        self.parts = []

    def add_part(self, part):
        self.parts.append(part)

    def clone(self):
        return copy.deepcopy(self)

prototype = Prototype()
prototype.add_part('part1')
clone = prototype.clone()
print(clone.parts)
```

输出:

```
['part1']
```

6. 适配器模式

适配器模式将一个类的接口转换成客户希望的另一个接口。这种模式常用于旧代码重用和接口不兼容的情况。

示例代码:

```python
class Rect:
    def get_size(self):
        return (0, 0)

class Square:
    def __init__(self, side):
        self.side = side

class SquareAdapter:
    def __init__(self, square):
        self.square = square

    def get_size(self):
        return (self.square.side, self.square.side)

square = Square(5)
adapter = SquareAdapter(square)
print(adapter.get_size())
```

输出:

```
(5, 5)
```

7. 装饰器模式

装饰器模式允许在运行时给对象添加功能。这种模式通常比继承更加灵活。

示例代码:

```python
class Component:
    def operation(self):
        pass

class ConcreteComponent(Component):
    def operation(self):
        return 'ConcreteComponent'

class Decorator(Component):
    def __init__(self, component):
        self.component = component

    def operation(self):
        return self.component.operation()

class ConcreteDecoratorA(Decorator):
    def __init__(self, component):
        self.component = component

    def operation(self):
        return self.component.operation() + ' + ConcreteDecoratorA'

class ConcreteDecoratorB(Decorator):
    def __init__(self, component):
        self.component = component

    def operation(self):
        return self.component.operation() + ' + ConcreteDecoratorB'

component = ConcreteComponent()
decorator_a = ConcreteDecoratorA(component)
decorator_b = ConcreteDecoratorB(decorator_a)
print(decorator_b.operation())
```

输出:

```
ConcreteComponent + ConcreteDecoratorA + ConcreteDecoratorB
```

8. 外观模式

外观模式通过定义一个高层接口,简化了客户端与复杂系统之间的交互。这种模式常用于管理大型系统。

示例代码:

```python
class SubSystemA:
    def do_task(self):
        print('SubSystemA: doing task...')

class SubSystemB:
    def do_task(self):
        print('SubSystemB: doing task...')

class SubSystemC:
    def do_task(self):
        print('SubSystemC: doing task...')

class Facade:
    def __init__(self):
        self.sub_system_a = SubSystemA()
        self.sub_system_b = SubSystemB()
        self.sub_system_c = SubSystemC()

    def do_task(self):
        self.sub_system_a.do_task()
        self.sub_system_b.do_task()
        self.sub_system_c.do_task()

facade = Facade()
facade.do_task()
```

输出:

```
SubSystemA: doing task...
SubSystemB: doing task...
SubSystemC: doing task...
```

9. 桥接模式

桥接模式将抽象和实现部分分离,从而使它们可以单独地进行变化。这种模式常用于实现多种变化,例如在图形用户界面中使用不同的主题。

示例代码:

```python
class DrawingAPI:
    def draw_circle(self, x, y, radius):
        pass

class DrawingAPI1(DrawingAPI):
    def draw_circle(self, x, y, radius):
        print(f'DrawingAPI1: circle with center ({x}, {y}) and radius {radius}')

class DrawingAPI2(DrawingAPI):
    def draw_circle(self, x, y, radius):
        print(f'DrawingAPI2: circle with center ({x}, {y}) and radius {radius}')

class Shape:
    def __init__(self, drawing_api):
        self.drawing_api = drawing_api

    def draw(self):
        pass

class CircleShape(Shape):
    def __init__(self, x, y, radius, drawing_api):
        super().__init__(drawing_api)
        self.x = x
        self.y = y
        self.radius = radius

    def draw(self):
        self.drawing_api.draw_circle(self.x, self.y, self.radius)

shape1 = CircleShape(1, 2, 3, DrawingAPI1())
shape1.draw()
shape2 = CircleShape(4, 5, 6, DrawingAPI2())
shape2.draw()
```

输出:

```
DrawingAPI1: circle with center (1, 2) and radius 3
DrawingAPI2: circle with center (4, 5) and radius 6
```

10. 组合模式

组合模式将对象组成树形结构,以表示部分-整体的层次结构,从而可以处理单个对象和组合对象的请求。这种模式常用于管理相似的对象,例如图形用户界面控件。

示例代码:

```python
class Component:
    def __init__(self, name):
        self.name = name

    def add(self, component):
        pass

    def remove(self, component):
        pass

    def display(self, depth):
        pass

class Leaf(Component):
    def add(self, component):
        print('Cannot add to a leaf')

    def remove(self, component):
        print('Cannot remove from a leaf')

    def display(self, depth):
        print('-' * depth + self.name)

class Composite(Component):
    def __init__(self, name):
        super().__init__(name)
        self.children = []

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

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

    def display(self, depth):
        print('-' * depth + self.name)
        for child in self.children:
            child.display(depth + 2)

root = Composite('root')
root.add(Leaf('leaf1'))
root.add(Leaf('leaf2'))
branch1 = Composite('branch1')
branch1.add(Leaf('leaf3'))
branch1.add(Leaf('leaf4'))
branch2 = Composite('branch2')
branch2.add(Leaf('leaf5'))
root.add(branch1)
root.add(branch2)
root.display(0)
```

输出:

```
root
--leaf1
--leaf2
--branch1
----leaf3
----leaf4
--branch2
----leaf5
```

11. 迭代器模式

迭代器模式提供一种方法来访问一个容器对象中的每个元素,而不暴露该对象的内部表示。这种模式常用于处理大型数据集合。

示例代码:

```python
class Iterator:
    def has_next(self):
        pass

    def next(self):
        pass

class ListIterator(Iterator):
    def __init__(self, data):
        self.data = data
        self.index = 0

    def has_next(self):
        return self.index < len(self.data)

    def next(self):
        if self.has_next():
            item = self.data[self.index]
            self.index += 1
            return item

class List:
    def __init__(self):
        self.data = []

    def add(self, item):
        self.data.append(item)

    def iterator(self):
        return ListIterator(self.data)

list = List()
list.add('item1')
list.add('item2')
list.add('item3')
iterator = list.iterator()
while iterator.has_next():
    item = iterator.next()
    print(item)
```

输出:

```
item1
item2
item3
```

12. 中介者模式

中介者模式定义了一个对象,它封装了一组对象的交互,并充当它们之间的中介。这种模式常用于处理复杂的通信和协议。

示例代码:

```python
class Mediator:
    def send(self, message, colleague):
        pass

class Colleague:
    def __init__(self, mediator):
        self.mediator = mediator

class ConcreteColleagueA(Colleague):
    def __init__(self, mediator):
        super().__init__(mediator)

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

    def receive(self, message):
        print(f'ConcreteColleagueA received "{message}"')

class ConcreteColleagueB(Colleague):
    def __init__(self, mediator):
        super().__init__(mediator)

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

    def receive(self, message):
        print(f'ConcreteColleagueB received "{message}"')

class ConcreteMediator(Mediator):
    def __init__(self, colleague_a, colleague_b):
        self.colleague_a = colleague_a
        self.colleague_b = colleague_b

    def send(self, message, colleague):
        if colleague == self.colleague_a:
            self.colleague_b.receive(message)
        else:
            self.colleague_a.receive(message)

colleague_a = ConcreteColleagueA(ConcreteMediator(None, None))
colleague_b = ConcreteColleagueB(colleague_a.mediator)
colleague_a.mediator = ConcreteMediator(colleague_a, colleague_b)
colleague_a.send('Hello, colleague B')
colleague_b.send('Hello, colleague A')
```

输出:

```
ConcreteColleagueB received "Hello, colleague A"
ConcreteColleagueA received "Hello, colleague B"
```

13. 备忘录模式

备忘录模式允许捕获一个对象的内部状态,并将其保存为一个备忘对象,以便稍后恢复该状态。这种模式常用于撤销和重做操作。

示例代码:

```python
class Memento:
    def __init__(self, state):
        self.state = state

class Originator:
    def __init__(self, state):
        self.state = state

    def create_memento(self):
        return Memento(self.state)

    def set_memento(self, memento):
        self.state = memento.state

    def display_state(self):
        print(f'Current state: {self.state}')

originator = Originator('State 1')
originator.display_state()
memento = originator.create_memento()
originator.state = 'State 2'
originator.display_state()
originator.set_memento(memento)
originator.display_state()
```

输出:

```
Current state: State 1
Current state: State 2
Current state: State 1
```

14. 解释器模式

解释器模式定义了一种语言的文法,并定义了一个解释器,用于解释语言中的句子。这种模式常用于编写编译器和解释器。

示例代码:

```python
class Expression:
    def interpret(self, context):