一:常见的代理模式 远程代理(Remote Proxy) 虚拟代理(Virtual Proxy) 保护代理(Protect Proxy) 缓存/缓冲代理(Cache Proxy) 智能引用代理(Smart Reference Proxy)shared_ptr 写时复制(copy-on-write)优化代理:string 防火墙代理、同步代理,复杂隐藏代理等。 二:范例学习 购物网站代理:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <type_traits>
#include <string>
using namespace std;
class WebAddr{
public:
virtual void visit() = 0;
virtual ~WebAddr() {}
};
class WebAddr_Shopping :public WebAddr{
public:
virtual void visit(){
cout << "访问WebAddr_Shopping购物网站!" << endl;
}
};
class WebAddr_Video :public WebAddr{
public:
virtual void visit(){
cout << "访问WebAddr_Video视频网站!" << endl;
}
};
class WebAddrProxy :public WebAddr{
public:
WebAddrProxy(WebAddr* pwebaddr) :mp_webaddr(pwebaddr) {}
public:
virtual void visit() {
mp_webaddr->visit();
}
private:
WebAddr* mp_webaddr;
};
class WebAddr_Shopping_Proxy :public WebAddr{
public:
virtual void visit(){
WebAddr_Shopping* p_webaddr = new WebAddr_Shopping();
p_webaddr->visit();
delete p_webaddr;
}
};
int main()
{
WebAddr* p = new WebAddr_Shopping();
p->visit();
WebAddr* p1 = new WebAddr_Shopping();
WebAddrProxy* p2 = new WebAddrProxy(p1);
p2->visit();
WebAddr* p3 = new WebAddr_Video();
WebAddrProxy* p4 = new WebAddrProxy(p3);
p4->visit();
delete p;
delete p1;
delete p2;
delete p3;
delete p4;
return 0;
}
缓存代理:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <type_traits>
#include <string>
using namespace std;
vector<string> g_fileItemList;
class ReadInfo {
public:
virtual void read() = 0;
virtual ~ReadInfo() {}
};
class ReadInfoFromFile : public ReadInfo
{
public:
virtual void read()
{
ifstream fin("test.txt");
if (!fin)
{
cout << "文件打开失败" << endl;
return;
}
string linebuf;
while (getline(fin, linebuf))
{
if (!linebuf.empty())
{
g_fileItemList.push_back(linebuf);
}
}
fin.close();
}
};
class ReadInfoProxy :public ReadInfo
{
public:
virtual void read()
{
if (!m_loaded)
{
m_loaded = true;
cout << "从文件中读取了如下数据---------:" << endl;
ReadInfoFromFile* rf = new ReadInfoFromFile();
rf->read();
delete rf;
}
else
{
cout << "从缓存中读取了如下数据----------:" << endl;
}
for (auto iter = g_fileItemList.begin(); iter != g_fileItemList.end(); ++iter)
{
cout << *iter << endl;
}
}
private:
bool m_loaded = false;
};
int main()
{
ReadInfo* preadinfoproxy = new ReadInfoProxy();
preadinfoproxy->read();
preadinfoproxy->read();
preadinfoproxy->read();
delete preadinfoproxy;
return 0;
}
|