学习完工厂策略模式,书中恰当的引入了设计模式职责的介绍。
本来简单描述了一下,后来看到了一篇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;
}