zoukankan      html  css  js  c++  java
  • 设计模式(4)---装饰模式

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

      如上UML所示,Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无须知道Decorator的存在的。至于ConcreteComponent就是具体的装饰对象,起到给Component添加职责的功能。

      

    #include "stdafx.h"
    #include <memory>
    #include <string>
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
        Person(string name = ""): name_(name)
        {}
        virtual void Show()
        {
            cout << "My name is :" << name_ << endl;
        }
    protected:
        string name_;
    };
    
    class Finery : public Person
    {
    public:
        void Decorator(shared_ptr<Person> person)
        {
            person_ = person;
        }
        virtual void Show()
        {
            if (nullptr != person_)
            {
                person_->Show();
            }
        }
    protected:
        shared_ptr<Person> person_;
    };
    
    class TShirt :public Finery
    {
    public:
        virtual void Show()
        {
            cout << "This is TShirt." << endl;
            person_->Show();
        }
    };
    
    class Sneaker : public Finery
    {
    public:
        virtual void Show()
        {
            cout << "This is Sneaker." << endl;
            person_->Show();
        }
    };
    
    int main()
    {
        auto person  = make_shared<Person>("cauchy");
        auto tshirt  = make_shared<TShirt>();
        auto sneaker = make_shared<Sneaker>();
        tshirt->Decorator(person);
        tshirt->Show();
        sneaker->Decorator(tshirt);
        sneaker->Show();
    
        return 0;
    }

      上例中的Person就相当于ConcreteComponent,而Finery就相当于Decorator,而Tshirt和Sneaker就是ConcreteComponent。

      总结:装饰模式是为已有功能动态地添加更多功能的一种方式,当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,他们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能都放在单独的类中,并让这个类包装他索要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象。并且,装饰模式能有效地把类的核心职责和装饰功能区分开来,而且可以去除相关类中重复的逻辑。

  • 相关阅读:
    ora-01847:月份中日的值必须介于 1 和当月最后一日之间
    (转)ORACLE中关于外键缺少索引的探讨和总结
    (转) Oracle性能优化-读懂执行计划
    shutdown immediate 持久无法关闭数据库之解决方案
    Oracle11g adump目录下面.aud增长导致空间撑满无法删除导致CRS无法启动的解决方法
    linux几种常见的文件内容查找和替换命令
    unzip解压3G或者4G以上文件失败的解决方法
    IMP-00058: ORACLE error 1882 encountered
    AIX文件系统/var空间100%的问题
    html5手机网站需要加的那些meta/link标签,html5 meta全解(转)
  • 原文地址:https://www.cnblogs.com/cauchy007/p/5331073.html
Copyright © 2011-2022 走看看