前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 实现装饰器设计模式

python 实现装饰器设计模式

作者头像
1_bit
发布2020-10-23 14:36:21
4041
发布2020-10-23 14:36:21
举报

python 装饰器简单、基本的实现并不复杂。装饰器(Decorators)模式类似于继承,当你需要为某一个对象添加额外的动作、行为时,在不改变类的情况下可以使用装饰器。这篇文就当做一篇水文,本来不想写,因为这个专栏是设计模式的多语言基本实现,不涉及过多内容,为了保证内容完整,所以只能直接塞进来了。

首先我们先新建一个人的基类,并且赋予几个属性(名字、性别、头发、衣服等),并且由两个基类,男人和女人:

class People():
    name = ""
    sex=""
    clothes = "没穿"
    hair="光头"
    sound_color=""

class Man(People):
    def __init__(self,name):
        self.name=name
        self.sex="男"
 
class Woman(People):
    def __init__(self,name):
        self.name=name
        self.sex="女" 

由于类以及新建,不进行改变,使用装饰器进行行为状态添加,是用装饰器。 新建一个装饰器基类,设置好装饰器方法,gethair 与 getclothes,再写两个类 hairDecorator与 dressedDecorator 继承于 exteriorDecorator,在装饰器 hairDecorator 中使对象长出头发,原有对象中头发的属性值是关头,在 dressedDecorator 中使对象穿上衣服,原有属性为没穿衣服。装饰器类如下:

class exteriorDecorator():#外形装饰基
    def gethair(self):
        pass
    def getclothes(self):
        pass
        
class hairDecorator(exteriorDecorator):#头发装饰
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def gethair(self):
        return str(self.people.name)+" 长出头发"

class dressedDecorator(exteriorDecorator):#外衣装饰
    def __init__(self,people):
        self.people=people
        self.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=name
        self.sex="男"
 
class Woman(People):
    def __init__(self,name):
        self.name=name
        self.sex="女" 


class exteriorDecorator():#外形装饰基
    def gethair(self):
        pass
    def getclothes(self):
        pass
        
class hairDecorator(exteriorDecorator):#头发装饰
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def gethair(self):
        return str(self.people.name)+" 长出头发"

class dressedDecorator(exteriorDecorator):#外衣装饰
    def __init__(self,people):
        self.people=people
        self.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())
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-07-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档