说下对代理模式的理解,代理模式就是用代理对象来替代实际对象,完成实际对象应该完成的操作,如给妹子送花, 或者打怪升级。
本质上, 他就是在访问对象的时候, 加入了一定程度的间接性, 通过这种间接性可以实现各种用途。
UML:
运行效果图
代码:
target.h
#ifndef _TARGET_H_
#define _TARGET_H_
#include <string>
class CTargetGirl{
public:
CTargetGirl(std::string name) : name(name){}
std::string Name() const { return name; }
void Name(std::string val) { name = val; }
private:
std::string name;
};
#endif // _TARGET_H_
operation.h
#ifndef _OPERATION_H_
#define _OPERATION_H_
class CIOperation{
public:
virtual void GiveDolls() const = 0;
virtual void GiveFlowers() const = 0;
virtual void GiveChocolates() const = 0;
};
#endif // _OPERATION_H_
persuit.h
#ifndef _PERSUIT_H_
#define _PERSUIT_H_
#include "target.h"
#include "operation.h"
#include <memory>
#include <iostream>
class CPersuit : public CIOperation{
public:
CPersuit(CTargetGirl * _girl) : girl(_girl){}
void GiveDolls() const { std::cout << girl->Name() << " give you dolls" << std::endl; }
void GiveFlowers() const { std::cout << girl->Name() << " give you flowers" << std::endl; }
void GiveChocolates() const { std::cout << girl->Name() << " give you chocolates" << std::endl; }
private:
CTargetGirl * girl;
};
#endif // _PERSUIT_H_
proxy.h
#ifndef _PROXY_H_
#define _PROXY_H_
#include "persuit.h"
#include "operation.h"
#include <memory>
#include <iostream>
class CProxy : public CIOperation{
public:
CProxy(CTargetGirl * _girl){ persuit = std::shared_ptr<CPersuit>(new CPersuit(_girl)); }
void GiveDolls() const { persuit->GiveDolls(); }
void GiveFlowers() const { persuit->GiveFlowers(); }
void GiveChocolates() const { persuit->GiveChocolates(); }
private:
std::shared_ptr<CPersuit> persuit;
};
#endif // _PROXY_H_
main.cpp
#include "proxy.h"
#include <iostream>
#include <memory>
using namespace std;
int main(){
shared_ptr<CTargetGirl> girl(new CTargetGirl("jiaojiao"));
shared_ptr<CProxy> proxy(new CProxy(girl.get()));
proxy->GiveDolls();
proxy->GiveFlowers();
proxy->GiveChocolates();
system("pause");
return 0;
}