代理模式与装饰器模式的区别在于,一个是”加料”,一个是”访问控制”
我是员工,想找老板,老板时间很宝贵,所以老板推出一个秘书,有什么事先告诉秘书,秘书先过滤一下访客,真正需要老板决定的再转告老板,这就是一种代理
另一个例子,在网络通讯中,存在两种代理:正向代理和反向代理,当client需要访问server的服务时,如果client在自己后面加一层代替自己访问server,server的结果只会反馈给加的这层,它感知不到背后真正访问的client,这就叫正向代理;如果server在自己前面加一层,client的请求先到加的这层,它感知不到背后真正在工作的server是谁,这就叫反向代理
以DNS查询为例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <iostream> #include <memory> #include <string> #include <unordered_map>
class DnsQuery { public: virtual std::string query(std::string host) = 0; virtual ~DnsQuery() {} };
class CNDns : public DnsQuery { public: std::string query(std::string host) override { std::cout << "cndns 查询中..." << std::endl; return host + ":10.10.10.10"; } };
class USDns : public DnsQuery { public: std::string query(std::string host) override { std::cout << "usdns 查询中..." << std::endl; return host + ":110.1.1.5"; } };
class ForwardProxy : public DnsQuery { public: std::string query(std::string host) override { if(host == "baidu.com") { return cn.query(host); } else { return us.query(host); } } private: CNDns cn; USDns us; };
class ReverseProxy : public DnsQuery { public: std::string query(std::string host) override { if(ip_map.count(host)) { return host + ":" + ip_map[host]; } std::string result = cn.query(host); ip_map[host] = result; return host + ":" + result; }
private: CNDns cn; std::unordered_map<std::string, std::string> ip_map; };
int main() { std::shared_ptr<DnsQuery> dns = std::make_shared<ForwardProxy>(); std::cout << dns->query("baidu.com") << std::endl; std::cout << dns->query("google.com") << std::endl;
std::cout << "=================================" << std::endl; ReverseProxy dns2; std::cout << dns2.query("baidu.com") << std::endl; std::cout << dns2.query("baidu.com") << std::endl; return 0; }
|