第6章 装饰模式

来源:互联网 发布:薇诺娜淘宝上是正品吗 编辑:程序博客网 时间:2024/05/22 17:33
装饰模式(Decorator):动态的给一个对象添加一些额外的指责,就增加功能来说,装饰模式比生成子类更为灵活。
component是定一个一个对象的借口,可以给这些对象动态的添加指责,conceretecomponent是定义的具体的对象,也可以给这个对象添加一些职责。decorator,装饰抽象类继承了component从外界来扩展component类的功能,但对于component来说,是无需知道decorator的存在的至于concretedecorator就是具体的装饰对象,起到给component添加责任的功能。
穿衣服是有顺序的从里到外。
装饰模式是利用setcomponent来对对象进行包装的,这样每个装饰对象的实现和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心被添加到对象链当中。
如果只有concretecomponent类而没有抽象的component类,那么decorator类可以是concretecomponent的一个子类,同样道理,如果只有一个concretedecorator类,那么就没有必要建立一个单独的decorator类,而可以把decorator和concretedecorator的责任合并成一个类。

程序:
person.h
#ifndef __PERSON_H__
#define __PERSON_H__  1

class Person
{
    public :
        Person(const char (&name)[20]);
        Person(const Person &person);
        Person(){};
        ~Person();
        void setName(const char (&name)[20]);//[ has more high priorty so we should use bracket.
        virtual void show() const;
    private:
        char _name[20];
};
#endif /*__PERSON_H__ */

person.cpp:


#include <iostream>
#include "person.h"
using std::cout;
using std::endl;
Person::Person(const char (&name)[20])
{
    strcpy(_name, name);
}
Person::Person(const Person &person)
{
    strcpy(_name, person._name);
}
void Person::setName(const char (&name)[20])
{
    strcpy(_name, name);
}
void Person::show() const
{
    cout << "I am " << _name << endl;
}
Person::~Person()
{

}


finery.h:

#ifndef __FINERY_H__
#define __FINERY_H__  1

#include "person.h"
class Finery : public Person
{
    public:
        inline void decotate(const Person *component){_component = component;}
        virtual void show() const;
    protected:
        const Person *_component;
};

class TShirts : public Finery
{
    public:
        virtual void show() const;
};
class BigTrouser :public  Finery
{
    public:
        virtual void show() const;

};
#endif /*__FINERY_H__ */

finery.cpp:


#include "finery.h"
#include <iostream>
using std::endl;
using std::cout;
void Finery::show() const
{
    if(_component != NULL)
    {
        _component->show();
    }   
}

void TShirts::show() const
{
    _component->show();
    cout << "tshirts"<<endl;
}
void BigTrouser::show() const
{
    _component->show();
    cout << "bigtrouser" <<endl;
}


main.cpp

#include <iostream>
#include "person.h"
#include "finery.h"
using std::cout;

int main(int argc, char *argv[])
{
    char name[20]= "lihai";
    Person tempPerson(name);


    BigTrouser *bT = new BigTrouser;
    TShirts *tS    = new TShirts;

    bT->decotate(&tempPerson);

    tS->decotate(bT);

    tS->show();
    return 0;
}


CMakeLists.txt:

project(decorator)

cmake_minimum_required(VERSION 2.6)

include_directories(./)

set(decorator_SRCS person.cpp finery.cpp main.cpp)

add_executable(decorator ${decorator_SRCS})


装饰模式是为已经有的功能动态的添加更多功能的一种方式。装饰模式提供了很好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类 包装它所要装饰的对象,因此当需要执行特殊行为时,客户代码就可以在运行时候根据需要有选择的按顺序的装饰功能包装对象了。
有效的分开核心指责和装饰功能