1.代理模式简介
代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。通俗的来讲代理模式就是我们生活中常见的中介。
2.源码实现
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(string name) : m_Name(name) {};
~Person() {};
virtual void rentHouse()
{
cout << m_Name << "需要租一间房子!" << endl;
}
private:
string m_Name;
};
//代理
class Intermediary : public Person
{
public:
Intermediary(string name, Person *person) : Person(name), m_Person(person) {};
~Intermediary() {};
void rentHouse()
{
m_Person->rentHouse();
cout << "中介抽取佣金百分之10!" << endl;
}
private:
Person *m_Person;
};
int main(int argc, char **argv)
{
Person *xiaoming = new Person("小明");
Person *xiaofang = new Intermediary("小芳", xiaoming);
xiaofang->rentHouse();
delete xiaofang;
delete xiaoming;
return 0;
}
3.编译源码
$ g++ -o example example.cpp
4.运行及其结果
$ ./example
小明需要租一间房子!
中介抽取佣金百分之10!
网友评论