python 装饰器简单、基本的实现并不复杂。装饰器(Decorators)模式类似于继承,当你需要为某一个对象添加额外的动作、行为时,在不改变类的情况下可以使用装饰器。这篇文就当做一篇水文,本来不想写,因为这个专栏是设计模式的多语言基本实现,不涉及过多内容,为了保证内容完整,所以只能直接塞进来了。
首先我们先新建一个人的基类,并且赋予几个属性(名字、性别、头发、衣服等),并且由两个基类,男人和女人:
class People():name = ""sex=""clothes = "没穿"hair="光头"sound_color=""class Man(People):def __init__(self,name):self.name=nameself.sex="男"class Woman(People):def __init__(self,name):self.name=nameself.sex="女"
由于类以及新建,不进行改变,使用装饰器进行行为状态添加,是用装饰器。
新建一个装饰器基类,设置好装饰器方法,gethair 与 getclothes,再写两个类 hairDecorator与 dressedDecorator 继承于 exteriorDecorator,在装饰器 hairDecorator 中使对象长出头发,原有对象中头发的属性值是关头,在 dressedDecorator 中使对象穿上衣服,原有属性为没穿衣服。装饰器类如下:
class exteriorDecorator():#外形装饰基def gethair(self):passdef getclothes(self):passclass hairDecorator(exteriorDecorator):#头发装饰def __init__(self,people):self.people=peopleself.sex="男"def gethair(self):return str(self.people.name)+" 长出头发"class dressedDecorator(exteriorDecorator):#外衣装饰def __init__(self,people):self.people=peopleself.sex="男"def getclothes(self):return str(self.people.name)+" 穿上外衣"
以上装饰器在初始化时传入了类对象。接下来新建一个对象小明与装饰器对象:
xiaoming=Man("小明")
xiaomingHariD=hairDecorator(xiaoming)
使用hairDecorator 方法装饰小明的头发,使用 dressedDecorator 装饰小明的上衣:
xiaomingHariD=hairDecorator(xiaoming)
xiaomingdressedD=dressedDecorator(xiaoming)
最后进行输出:
print(xiaomingHariD.gethair())
print(xiaomingdressedD.getclothes())
结果如下:
完整代码如下:
class People():name = ""sex=""clothes = "没穿"hair="光头"sound_color=""class Man(People):def __init__(self,name):self.name=nameself.sex="男"class Woman(People):def __init__(self,name):self.name=nameself.sex="女" class exteriorDecorator():#外形装饰基def gethair(self):passdef getclothes(self):passclass hairDecorator(exteriorDecorator):#头发装饰def __init__(self,people):self.people=peopleself.sex="男"def gethair(self):return str(self.people.name)+" 长出头发"class dressedDecorator(exteriorDecorator):#外衣装饰def __init__(self,people):self.people=peopleself.sex="男"def getclothes(self):return str(self.people.name)+" 穿上外衣"xiaoming=Man("小明")
print(xiaoming.name)
xiaomingHariD=hairDecorator(xiaoming)
xiaomingdressedD=dressedDecorator(xiaoming)
print(xiaomingHariD.gethair())
print(xiaomingdressedD.getclothes())