提出的动机来源于对继承的乱用导致的派生类急速增加的问题。 主要是要分清楚积累的派生分别是往“主体”走的or往“拓展”走的 装饰器模式特征一般比较明显,父类在被派生类继承的同时也被包含了 (用侯捷老师的话是委托delegation,因为这里用的是指针)。
#pragma once
#include <iostream>
using namespace std;
template<typename T>
class component {
public:
virtual void _charactor() {}
virtual void attch() {}
virtual void describe() {}
};
template<typename T>
class component1 :public component<T> {
public:
virtual void _charactor() {
cout << "一类人员";
}
};
template<typename T>
class component2 : public component<T> {
public:
virtual void _charactor() {
cout << "二类人员" ;
}
};
template<typename T>
class decorator :public component<T> {
public:
virtual void _charactor() {
Component->_charactor();
}
virtual void describe() {
attach();
cout << endl;
}
protected:
decorator(component<T>* com) :Component(com) {}
component<T>* Component;
virtual void attach() {
cout << "存放附加属性的虚函数" << endl;
}
};
template<typename T>
class dec_1component :public decorator<T> {
protected:
virtual void attach() {
cout << " 又被装饰器1装饰了 ";
}
public:
dec_1component(component<T>* com) :decorator<T>(com) {}
};
template<typename T>
class dec_2component :public decorator<T> {
protected:
virtual void attach() {
cout << " 又被装饰器2装饰了 ";
}
public:
dec_2component(component<T>* com) :decorator<T>(com) {}
};
调用接口:
cout << "测试装饰器模式" << endl;
component1<int>* Lihua = new component1<int>;
dec_1component<int>* Lihua_1 = new dec_1component(Lihua);
dec_2component<int>* Lihua_2 = new dec_2component(Lihua);
dec_2component<int>* Lihua_12 = new dec_2component(Lihua_1);
Lihua->describe();
Lihua_1->describe();
Lihua_2->describe();
Lihua_12->describe();
|