设计模式实现(三)---装饰模式

来源:互联网 发布:java throws用法 编辑:程序博客网 时间:2024/04/29 20:06


装饰者模式实现概要

#include <stdio.h>#include <string.h>//Component类class Component{public:virtual void Operation() = 0;};//ConcreteComponent类class ConcreteComponent : public Component{public:void Operation(){printf("具体的操作对象 \n");}};//Decorator类class Decorator : Component{protected:Component *component;public:Decorator(Component *comp):component(comp){}//带comp的构造函数Decorator():component(NULL){}public:virtual void Operation()//重写构造函数{if(component != NULL){component->Operation();}}void setComponent(Component *comp){component = comp;}};class ConcreteDecoratorA : public Decorator{private:char newState[30];//本类装饰的新属性public:void Operation(){Decorator::Operation();//先运行原Component的Operation(),再执行本类的功能,如newState就相当于对原Component进行了装饰strcpy(newState,"New State");printf("具体装饰对象A装饰了新属性:%s \n",newState);}};class ConcreteDecoratorB : public Decorator{public:void Operation(){Decorator::Operation();AddedBehavior();}private:void AddedBehavior()//本类独有的方法{printf("具体装饰对象B装饰了新方法\n");}};//如果只有一个ConcreteComponent类而没有抽象的Component类,//那么Decortor类可以使ConcreteComponent的一个子类。//同样道理,如果只有一个ConcreteDecorator类,那么就没有必要简历一个单独的Decorator类,//而可以把Decorator和ConcreteDecorator的责任合并成一个类。/*装饰者模式是为已有功能动态的添加更多功能的一种方式。当系统需要新功能的时候,向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。它们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才回执行的特殊行为的需要。而装饰者模式就提供了一个很好得解决方案,它把每个要装饰的功能放在单个类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择的、按顺序地使用装饰功能包装对象了。总结来说,装饰模式的有点事把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。*/int main(){ConcreteComponent *c = new ConcreteComponent();ConcreteDecoratorA d1;ConcreteDecoratorB d2;//装饰的方法是:首先用ConcreteComponent实例化对象c,然后用//ConcreteDecoratorA的实例化对象d1来包装c,//再用ConcreteDecoratorB的实例化对象d2包装d1,//最终执行d2的Operation//执行的顺序是先执行c的,再执行d1的,再执行d2的 d1.setComponent(c);d2.setComponent((Component *)&d1);//d1.Operation();d2.Operation();return 1;}

装饰者模式实现例子(穿衣服的小程序)

//利用装饰者模式做一个穿衣服的小程序#include <string>#include <stdio.h>//Person类,(ConcreteComponent)class Person{public:Person(){}Person(char *name){strcpy(this->name,name);}public:virtual void show(){printf("装扮的 %s\n",name);}private:char name[20];};class Finery : public Person{private:Person *component;public:Finery(){component = NULL;}virtual void show(){if(component != NULL)component->show();}virtual void setCompent(Person *component){this->component = component;}};//具体服饰类(ConcreteDecorator)class TShirts : public Finery{public:void show(){printf(" T Shirt ");Finery::show();}};class BigTrouser : public Finery{public:void show(){printf(" BigTrouser ");Finery::show();}};class Sneakers : public Finery{public:void show(){printf(" Sneakers ");Finery::show();}};int main(){Person cx("小菜");Sneakers pqx;BigTrouser kk;TShirts dtx;pqx.setCompent(&cx);//装饰过程kk.setCompent(&pqx);dtx.setCompent(&kk);dtx.show();return 1;}


0 0
原创粉丝点击