结构型模式-代理模式
代理模式
- 为其他对象提供一种代理,以控制对这个对象的访问
- 代理模式的UML图:
说明:用户想要购买国外产品需要通过代购,代购在购买(Buy方法)过程中可以进行其他操作,加点小费、帮你验证产品真假,是真的才帮你购买等等。
物品
class Item
{
public:
Item(string kind, bool type)
{
m_kind = kind;
m_type = type;
}
string GetKind()
{
return m_kind;
}
bool GetFact()
{
return m_type;
}
private:
string m_kind;
bool m_type;
};
Shoping抽象类
class Shoping
{
public:
virtual void Buy(Item* item) = 0;
};
每个国家购物实现
class USA_Shoping :public Shoping
{
public:
virtual void Buy(Item* item)
{
cout << "买了一个美国的" << item->GetKind() << endl;
}
};
class Korea_Shoping :public Shoping
{
public:
virtual void Buy(Item* item)
{
cout << "买了一个韩国的" << item->GetKind() << endl;
}
};
class Japan_Shoping :public Shoping
{
public:
virtual void Buy(Item* item)
{
cout << "买了一个日本的" << item->GetKind() << endl;
}
};
代理类实现
class OverseasProxy :public Shoping
{
public:
OverseasProxy(Shoping* shoping)
{
ShopingCounry = shoping;
}
virtual void Buy(Item* item)
{
if (item->GetFact()==true)
{
cout << "是正品,能购买" << endl;
ShopingCounry->Buy(item);
}
else
{
cout << "是假货,不购买" << endl;
}
}
private:
Shoping * ShopingCounry;
};
客户
int main(void)
{
Item washing_powder("碧浪",false);
Item facial_mask("一叶子", true);
Item comic_book("七龙珠", true);
Shoping* shopingarea = new Korea_Shoping;
Shoping* shopingproxy = new OverseasProxy(shopingarea);
shopingproxy->Buy(&facial_mask);
return 0;
}
结果:
-
优点:
(1)增加和更换代理类无须修改源代码,符合开闭原则,系统具
有较好的灵活性和可扩展性 -
缺点:
(1)代理类实现较为复杂
- 使用场景:
为其他对象提供一种代理以控制对这个对象的访问