[cpp]
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
/*
代理模式 :追女生問題(大話設計模式中的案例)
*/
/*共同的接口*/
class givegift
{ public:
virtual void givedolls() = 0;
virtual void giveflowers() = 0;
virtual void givechocolate() = 0;
};
class schoolgirl
{
private:
string name;
public:
void set_name(string name)
{
this->name = name;
}
string get_name()
{
return name;
}
};
// 追求者
class pursuit: public givegift
{
schoolgirl mm;
public:
pursuit(schoolgirl mm)
{
this->mm = mm;
}
void givedolls()
{
cout <<mm.get_name()<<"送你洋娃娃"<< endl;
}
void giveflowers()
{
cout <<mm.get_name()<<"送你花兒"<< endl;
}
void givechocolate()
{
cout <<mm.get_name()<<"送你巧克力"<< endl;
}
};
//代理
class proxy: givegift
{
pursuit *gg;
public:
proxy(schoolgirl *mm)
{
gg = new pursuit(*mm);
}
void givedolls()
{
gg->givedolls();
}
void giveflowers()
{
gg->giveflowers();
}
void givechocolate()
{
gg->givechocolate();
}
};
//相當於客戶端
int main()
{
schoolgirl *jiaojiao = new schoolgirl();
jiaojiao->set_name("李嬌嬌:");
proxy *daili = new proxy(jiaojiao);
daili->givedolls();
daili->giveflowers();
daili->givechocolate();
system("pause");
return 0;
}
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
/*
代理模式 :追女生問題(大話設計模式中的案例)
*/
/*共同的接口*/
class givegift
{ public:
virtual void givedolls() = 0;
virtual void giveflowers() = 0;
virtual void givechocolate() = 0;
};
class schoolgirl
{
private:
string name;
public:
void set_name(string name)
{
this->name = name;
}
string get_name()
{
return name;
}
};
// 追求者
class pursuit: public givegift
{
schoolgirl mm;
public:
pursuit(schoolgirl mm)
{
this->mm = mm;
}
void givedolls()
{
cout <<mm.get_name()<<"送你洋娃娃"<< endl;
}
void giveflowers()
{
cout <<mm.get_name()<<"送你花兒"<< endl;
}
void givechocolate()
{
cout <<mm.get_name()<<"送你巧克力"<< endl;
}
};
//代理
class proxy: givegift
{
pursuit *gg;
public:
proxy(schoolgirl *mm)
{
gg = new pursuit(*mm);
}
void givedolls()
{
gg->givedolls();
}
void giveflowers()
{
gg->giveflowers();
}
void givechocolate()
{
gg->givechocolate();
}
};
//相當於客戶端
int main()
{
schoolgirl *jiaojiao = new schoolgirl();
jiaojiao->set_name("李嬌嬌:");
proxy *daili = new proxy(jiaojiao);
daili->givedolls();
daili->giveflowers();
daili->givechocolate();
system("pause");
return 0;
}
總結:
這個模式就是用代理者將對代理者進行包裝,並且繼承共同的接口;其中GoF 對其定義是:
為其它對象提供一種代理以控制對這個對象的訪問。