概念
代理模式:爲其他對象提供一種代理以控制對這個對象的訪問
使用場景
- 想在訪問一個類時做一些控制;
- 直接訪問對象時會帶來的問題,比如說:要訪問的對象在遠程的機器上。
一般步驟
- 將被代理者和代理者的共同行爲抽象出來作爲一個類;
class GiveGift // 送禮物類 { public: virtual void GiveDolls() = 0; virtual void GiveFlowers() = 0; virtual void GiveChocolate() = 0; };
- 寫被代理者的類;
class Pursuit : public GiveGift // 被代理者-追求者類 { public: Pursuit(SchoolGirl *mm) { this->mm = mm; } void GiveDolls() { cout << mm->name << "送你洋娃娃" << endl; } void GiveFlowers() { cout << mm->name << "送你鮮花" << endl; } void GiveChocolate() { cout << mm->name << "送你巧克力" << endl; } private: SchoolGirl *mm; };
- 寫代理者類,裏面的行爲全部調用被代理者的行爲;
class Proxy : public GiveGift // 代理類 { public: Proxy(SchoolGirl *mm) { gg = new Pursuit(mm); } void GiveDolls() { gg->GiveDolls(); } void GiveFlowers() { gg->GiveFlowers(); } void GiveChocolate() { gg->GiveChocolate(); } private: Pursuit *gg; // 被代理者 };
具體實例
// 04Proxy.cpp
#include <iostream>
#include <string>
using namespace std;
class SchoolGirl // 女孩類
{
public:
SchoolGirl(string name)
{
this->name = name;
}
string name;
};
class GiveGift // 送禮物類
{
public:
virtual void GiveDolls() = 0;
virtual void GiveFlowers() = 0;
virtual void GiveChocolate() = 0;
};
class Pursuit : public GiveGift // 被代理者-追求者類
{
public:
Pursuit(SchoolGirl *mm)
{
this->mm = mm;
}
void GiveDolls()
{
cout << mm->name << "送你洋娃娃" << endl;
}
void GiveFlowers()
{
cout << mm->name << "送你鮮花" << endl;
}
void GiveChocolate()
{
cout << mm->name << "送你巧克力" << endl;
}
private:
SchoolGirl *mm;
};
class Proxy : public GiveGift // 代理類
{
public:
Proxy(SchoolGirl *mm)
{
gg = new Pursuit(mm);
}
void GiveDolls()
{
gg->GiveDolls();
}
void GiveFlowers()
{
gg->GiveFlowers();
}
void GiveChocolate()
{
gg->GiveChocolate();
}
private:
Pursuit *gg; // 被代理者
};
int main()
{
SchoolGirl *jiaojiao = new SchoolGirl("李嬌嬌");
Proxy *DaiLi = new Proxy(jiaojiao);
DaiLi->GiveDolls();
DaiLi->GiveFlowers();
DaiLi->GiveChocolate();
return 0;
}
參考資料
《大話設計模式》