想要实现强化内部原有功能,并且尽可能多的保留原有功能?
试试代理模式!
智能指针
auto p=make_shared<classname>();
虚拟代理
虚拟代理可以实现懒汉式的方法,初始化时仅保存路径,使用时才真正调用进内存
using namespace std;
struct Image {
virtual void draw() = 0;
};
struct LazeImage :Image {
public:
LazeImage(string& filename) :filename{filename}{}
~LazeImage() { delete bmp; }
void draw() {
if (!bmp) bmp = new string(filename);
bmp->draw();
}
private:
char* bmp{ nullptr };
string filename;
};
值代理
值代理表示对值的代理,封装数据,根据用途实现功能的增强。
using namespace std;
template<typename T>struct Value {
virtual operator T() const = 0;
};
template<typename T> struct Oneof :Value<T> {
vector<T> data;
Oneof() :data{ {T{}} } {}
Oneof(initializer_list<T> data) :data{ data } {} //initializer_list<T>为初始化列表的参数形式,适用于初始化列表方式进行初始化的时候
operator T() const override {
return data[rand() % data.size()];//返回随机数
}
};
int main()
{
Oneof<int> stuff{ 1,2,3,4,5,6,7,8,9,10 };
cout << stuff << endl << stuff << endl << stuff << endl << stuff << endl << stuff << endl << stuff;
}
总结
我们可以的看到,代理模式相比于装饰器模式,不会尝试通过添加新成员扩展功能,而是强化现有成员的潜在行为,代理主要作为一种替代品