Posts 设计模式-装饰模式
Post
Cancel

设计模式-装饰模式

概念解析

装饰模式,指的是动态地给一个对象增加一些额外的职责,就拓展对象来说,装饰模式比生成子类的方式更加灵活。功能上看,和Python自带的装饰器类似,但是装饰模式更倾向于从设计模式的角度,通常是修饰某个类的指定方法(装饰器用法更多更杂)。其设计的要点是:

  • 可以灵活地进行对象的职责添加和拓展功能
  • 可增加任意多个装饰
  • 装饰的顺序不一样,可能产生不同的效果

其类图如下: img

设计模板

装饰模式通常是设计一个装饰器,Python而言,通常有两种:修饰函数/修饰类。具体可参见:Python-常用装饰器

实例分析

简单样例:给Person类添加 wear 接口,能够提供不同的实现(不同人穿不同衣服):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from abc import ABCMeta, abstractmethod


class Person(metaclass=ABCMeta):
    "人"

    def __init__(self, name):
        self._name = name

    @abstractmethod
    def wear(self):
        print("着装:")


class Engineer(Person):
    "工程师"

    def __init__(self, name, skill):
        super().__init__(name)
        self.__skill = skill

    def getSkill(self):
        return self.__skill

    def wear(self):
         print("我是 " + self.getSkill() + "工程师 " + self._name, end=", ")
         super().wear()


class Teacher(Person):
    "教师"

    def __init__(self, name, title):
        super().__init__(name)
        self.__title = title

    def getTitle(self):
        return self.__title

    def wear(self):
         print("我是 " + self._name + self.getTitle(), end=", ")
         super().wear()


class ClothingDecorator(Person):
    "服装装饰器的基类"

    def __init__(self, person):
        self._decorated = person

    def wear(self):
        self._decorated.wear()
        self.decorate()

    @abstractmethod
    def decorate(self):
        pass


class CasualPantDecorator(ClothingDecorator):
    "休闲裤装饰器"

    def __init__(self, person):
        super().__init__(person)

    def decorate(self):
        print("一条卡其色休闲裤")


def BeltDecorator(ClothingDecorator):
    "腰带装饰器"

    def __init__(self, person):
        super().__init__(person)

    def decorate(self):
        print("一条银色针扣头的黑色腰带")


def testDecorator():
    tony = Engineer("Tony", "客户端")
    decoratedengineer = GlassesDecorator(BeltDecorator(tony))
    decoratedteacher = GlassesDecorator(BeltDecorator(Teacher("wells", "教授")))
This post is licensed under CC BY 4.0 by the author.

设计模式-职责模式

设计模式-构建模式