1.UML
2.代码
#include <iostream>
using namespace std;
class Subject{
public:
virtual void Request() = 0;
};
class RealSubject:public Subject
{
public:
virtual void Request(){
cout << "RealSubject" << endl;
}
};
class Proxy:public Subject
{
public:
RealSubject *real = nullptr;
virtual void Request(){
if(real == nullptr){
real = new RealSubject();
}
real->Request();
}
};
class Client{
public:
void dothing(Subject *object){
object->Request();
}
};
int main()
{
Client *c = new Client();
Proxy *p = new Proxy();
c->dothing(p);
cout << "--endl--" << endl;
return 0;
}
运行结果:
RealSubject
--endl--
练习:追求者
UML图
#include <iostream>
using namespace std;
class Songliwu{
public:
virtual void song_wawa() = 0;
virtual void song_huahua() = 0;
virtual void song_qiaokeli() = 0;
};
class MM{
public:
string name;
MM(string _name):name(_name){
}
};
class Persuit:public Songliwu
{
public:
MM *mm;
Persuit(MM *_mm):mm(_mm){
}
void song_wawa(){
cout << mm->name <<":送娃娃" << endl;
}
void song_huahua(){
cout << mm->name <<":送花花" << endl;
}
void song_qiaokeli(){
cout << mm->name <<":送巧克力" << endl;
}
};
class Proxy:public Songliwu
{
public:
Persuit *gg;
Proxy(MM *mm){
gg = new Persuit(mm);
}
void song_wawa(){
gg->song_wawa();
}
void song_huahua(){
(*gg).song_huahua();
}
void song_qiaokeli(){
(*gg).song_qiaokeli();
}
};
int main(void)
{
MM *mm = new MM("韩梅梅");
Proxy p(mm);
p.song_wawa();
p.song_huahua();
p.song_qiaokeli();
cout << "--endl--" << endl;
return 0;
}
运行结果:
韩梅梅:送娃娃
韩梅梅:送花花
韩梅梅:送巧克力
--endl--
参考:https://lkmao.blog.csdn.net/article/details/128950278?ydreferer=aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3l1ZW5pX3poYW8vY2F0ZWdvcnlfMTIxNDI1MDUuaHRtbA%3D%3D