设计模式---装饰模式(decorator)

装饰模式(decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

说白了就是扩展一个类的功能,而又不想用继承。

不废话先看UML和一段代码吧:

对应代码:

#include <iostream>
using namespace std;

class People
{
    public:
    People(string name,string profession):Name(name),Profession(profession){}
    virtual void Introduce_slef() = 0;
    void IntroduceName()
    {
        cout << "My name is: " << Name << endl;
    }
    void IntroduceProfession()
    {
        cout << "My profession is: " << Profession << endl;
    }
    private:
    string Name;
    string Profession;
};

class Student:public People
{
    public:
    Student(string name,string profession,string school):People(name,profession)
                ,School(school){}
    void Introduce_slef()
    {
        IntroduceName();
        IntroduceProfession();
    }
    void Learn()
    {

    }
    //other interface
    private:
    string School;
};

class Teacher:public People
{
    public:
    Teacher(string name,string profession,int year):People(name,profession),
                WorkYear(year){}
    void Introduce_slef()
    {
        IntroduceName();
        IntroduceProfession();
    }
    void Teach()
    {

    }
    //other interface
    private:
    int WorkYear;
};


class DecoratorPeople
{
    public:
    DecoratorPeople(int id):ID(id),pl(NULL){}
    void Decorator(People *p)
    {
        pl = p;
    }
    void IntroduceId()
    {
        cout << "My ID is: " << ID << endl;
    }
    void Introduce_slef()
    {
        IntroduceId();
        pl->Introduce_slef();
    }
    private:
    int ID;
    People *pl;
};
int main()
{
    People *p = new Teacher("xiaozhang","teacher",5);
    People *p1 = new Student("xiaowang","student","New York");
    DecoratorPeople md(3001);
    md.Decorator(p);
    md.Introduce_slef();
    md.Decorator(p1);
    md.Introduce_slef();
    delete p;
    delete p1;
    return 0;
}

据上述UML图和代码我们来介绍一下什么叫装饰模式,它是如何起到添加功能的作用的。

抽象了一个People类,派生了Student和Teacher两个具体类,

从抽象类又派生了一个DecoratorPeople类,这个类来给People添加功能,就是所谓的装饰类

这里其实就是对多态的灵活运用,研究了这么长时间本人认为所有设计模式都是对多态的灵活运用,离开多态一切免谈。要不然c语言为什么没有设计模式?

职责单一原则,依赖倒转原则,开放封闭原则这里几乎全部用到了。

设计模式也就是以原则为前提,灵活运用多态,然后考虑实际应用程序可能的维护和扩展,其实也并不深奥。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值