设计模式复习-装饰模式

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

 

2. 装饰模式是利用SetComponent来对对象进行包装的。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。

3. 如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类,同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。


代码:

#pragma once
#include "stdafx.h"
#include<iostream>
#include<windows.h>
using namespace std;

class Component {
public:
	virtual VOID Operator() = 0;
};

class ConcreteComponent :public Component {
public:
	VOID Operator() {
		cout << "具体操作对象" << endl;
	}
};

class Decorator :public Component {
private:
	Component * mpComponent = NULL;
public:
	VOID SetComponent(Component * pComponent) {
		mpComponent = pComponent;
	}
	VOID Operator() {
		if (mpComponent != NULL) {
			mpComponent->Operator();
		}
	}
};

class ConcreteDecoratorA :public Decorator {
public:
	VOID Operator() {
		Decorator::Operator();
		cout << "具体装饰对象A的操作" << endl;
	}
};

class ConcreteDecoratorB :public Decorator {
public:
	VOID Operator() {
		Decorator::Operator();
		cout << "具体装饰对象B的操作" << endl;
	}
};

int main()
{
	
	ConcreteComponent *pPeople = new ConcreteComponent();    //定义一个人
	ConcreteDecoratorA *pClothesA = new ConcreteDecoratorA();//A衣服
	ConcreteDecoratorB *pClothesB = new ConcreteDecoratorB();//B衣服


	pClothesA->SetComponent(pPeople);  //穿A衣服
	pClothesB->SetComponent(pClothesA);//继续穿上B衣服
	pClothesB->Operator();             //showtime

	delete pPeople, delete pClothesA, delete pClothesB;

	getchar();
	return 0;
}

原文地址:https://www.cnblogs.com/csnd/p/12061925.html