简介
代理模式为其他对象提供一个代理,可以控制对这个对象的访问
也就是说在访问这个对象的时候,可以添加一些重复的代码至代理类中,减少调用时的代码量。
不用代理模式
#include<iostream>
using namespace std;
#include<string>
class Item
{
public:
Item(string kind,bool flag)
{
this->flag = flag;
this->kind = kind;
}
string kind;
bool flag;
};
class Shopping
{
public:
virtual void buy(Item *it)=0;
};
class ChinaShop:public Shopping
{
public:
void buy(Item *it)
{
cout<<"在中国商场买了:"<<it->kind<<endl;
}
};
class JapanShop:public Shopping
{
public:
void buy(Item *it)
{
cout<<"在日本商场买了:"<<it->kind<<endl;
}
};
int main()
{
Item it1("衣服",true);
Item it2("手机",false);
Shopping *shop1 = new ChinaShop;
Shopping *shop2 = new JapanShop;
if(it1.flag)
{
cout<<"是正品"<<endl;
shop1->buy(&it1);
}
else
{
cout<<"是赝品"<<endl;
}
if(it2.flag)
{
shop2->buy(&it2);
cout<<"是正品"<<endl;
}
else
{
cout<<"是赝品"<<endl;
}
system("pause");
return 0;
}
可以看到,在主函数中需要写两遍if判断是否是正品,导致主函数代码较多较乱
使用代理模式
#include<iostream>
using namespace std;
#include<string>
class Item
{
public:
Item(string kind,bool flag)
{
this->flag = flag;
this->kind = kind;
}
string kind;
bool flag;
};
class Shopping
{
public:
virtual void buy(Item *it)=0;
};
class ChinaShop:public Shopping
{
public:
void buy(Item *it)
{
cout<<"在中国商场买了:"<<it->kind<<endl;
}
};
class JapanShop:public Shopping
{
public:
void buy(Item *it)
{
cout<<"在日本商场买了:"<<it->kind<<endl;
}
};
//代理者
class Proxy:public Shopping
{
public:
Proxy(Shopping *shop)
{
this->shop = shop;
}
void buy(Item *it)
{
if(it->flag)
{
cout<<"是正品"<<endl;
shop->buy(it);
}
else
{
cout<<"是赝品"<<endl;
}
}
private:
Shopping *shop;
};
int main()
{
Item it1("衣服",true);
Item it2("手机",false);
Shopping *chinashop = new ChinaShop;
Shopping *proxy = new Proxy(chinashop);
proxy->buy(&it1);
proxy->buy(&it2);
system("pause");
return 0;
}
可以看到,主函数中代码量明显较少,并且逻辑清晰。
动态代理模式
上述代理模式是一个静态代理模式,下面是动态代理
#include<iostream>
using namespace std;
#include<string>
class Item
{
public:
virtual void set(string kind,bool flag)=0;
string kind;
bool flag;
};
class shoe:public Item
{
public:
shoe()
{
}
void set(string kind,bool flag)
{
this->flag = flag;
this->kind = kind;
}
};
class Shopping
{
public:
virtual void buy(Item *it)=0;
};
class ChinaShop:public Shopping
{
public:
void buy(Item *it)
{
cout<<"在中国商场买了:"<<it->kind<<endl;
}
};
class JapanShop:public Shopping
{
public:
void buy(Item *it)
{
cout<<"在日本商场买了:"<<it->kind<<endl;
}
};
//代理者
class Proxy:public Shopping
{
public:
Proxy(Shopping *shop)
{
this->shop = shop;
}
void buy(Item *it)
{
if(it->flag)
{
cout<<"是正品"<<endl;
shop->buy(it);
}
else
{
cout<<"是赝品"<<endl;
}
}
private:
Shopping *shop;
};
int main()
{
Item *ite3 = new shoe;
ite3->set("yifu",true);
Shopping *chinashop = new ChinaShop;
Shopping *proxy = new Proxy(chinashop);
proxy->buy(ite3);
system("pause");
return 0;
}
总结
优点: 职责清晰;高扩展性;智能化
缺点:引入了另一个抽象层;影响速度