大话设计模式笔记——装饰模式(C++换装实现)

学习完工厂策略模式,书中恰当的引入了设计模式职责的介绍。

本来简单描述了一下,后来看到了一篇blog,有案例代码的比对,写得非常详细,也参考了一下大话设计模式,地址在下面。

设计模式六大原则http://www.uml.org.cn/sjms/201211023.asp


一直觉得我的抽象思维能力比较差,也可能是比较菜,理解的不是很深。希望以后经验足够了,回头来再看不需要走弯路。

仔细阅读下面的代码,关键在于Show()函数的重载,它使得穿不同服饰子类的实现和如何穿服饰隔离开,我们只需要关心穿服饰的实现,可以在里面任意做其他的补充逻辑。


装饰模式动态的给一个对象添加额外的职责,比增加子类灵活的多。

//
//  main.cpp
//  Decorator
//
//  Created by Ben_22 on 14-5-29.
//  Copyright (c) 2014年 Ben_22. All rights reserved.
//

#include <iostream>
#include "string"
using namespace std;

class Person{
public:
    Person(){};
    Person(string name){
        this->name = name;
    }
    
    virtual void Show(){
        cout<<"装扮者:"<<name<<endl;
    }
private:
    string name;
    
};


class Finery : public Person{
protected:
    Person *component;
public :
    void Decorate( Person *component){
        this->component = component;
    }
    
    void Show() override{
        if (component != nullptr) {
            component->Show()  ;
        }
    }
};


class TShirts : public Finery{
public:
    void Show() override{
        cout<<"T恤"<<endl;
        Finery::Show();
    }
};

class BigThouser : public Finery{
public:
    void Show() override{
        cout<<"大裤衩"<<endl;
        Finery::Show();
    }
};

class Shoes : public Finery{
public:
    void Show() override{
        cout<<"鞋子"<<endl;
        Finery::Show();
    }
};

class Tie : public Finery{
public:
    void Show() override{
        cout<<"领带"<<endl;
        Finery::Show();
    }
};

int main(int argc, const char * argv[])
{
    Person *xc = new Person("小菜");
    
    cout<<"第一种装扮"<<endl;
    TShirts *dtx = new TShirts();
    BigThouser *kk = new BigThouser();
    
    dtx->Decorate(xc);
    kk->Decorate(dtx);
    kk->Show();
    
    cout<<"第二种装扮"<<endl;
    Shoes *sh = new Shoes();
    Tie *ti = new Tie();
    
    sh->Decorate(xc);
    ti->Decorate(sh);
    ti->Show();
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值