结构性模式:关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。
代理模式Proxy:
class VideoSite
{
public:
virtual void freeMovie() = 0;
virtual void vipMovie() = 0;
virtual void ticketMovie() = 0;
};
class FixBugVideoSite : public VideoSite
{
public:
virtual void freeMovie()
{
cout << "观看免费电影" << endl;
}
virtual void vipMovie()
{
cout << "观看VIP电影" << endl;
}
virtual void ticketMovie()
{
cout << "用券观看电影" << endl;
}
};
class FreeVideoSiteProxy : public VideoSite
{
public:
virtual void freeMovie()
{
Video.freeMovie();
}
virtual void vipMovie()
{
cout << "您目前只是普通游客,需要升级成VIP,才能观看VIP电影" << endl;
}
virtual void ticketMovie()
{
cout << "您目前没有券,需要购买电影券,才能观看电影" << endl;
}
private:
FixBugVideoSite Video;
};
class VipVideoSiteProxy : public VideoSite
{
public:
VipVideoSiteProxy() { pVideo = new FixBugVideoSite(); }
~VipVideoSiteProxy() { delete pVideo; }
virtual void freeMovie()
{
pVideo->freeMovie();
}
virtual void vipMovie()
{
pVideo->vipMovie();
}
virtual void ticketMovie()
{
cout << "您目前没有券,需要购买电影券,才能观看电影" << endl;
}
private:
VideoSite *pVideo;
};
void watchMovice(unique_ptr<VideoSite> &ptr)
{
ptr->freeMovie();
ptr->vipMovie();
ptr->ticketMovie();
}
int main()
{
unique_ptr<VideoSite> p1(new FreeVideoSiteProxy());
unique_ptr<VideoSite> p2(new VipVideoSiteProxy());
watchMovice(p1);
watchMovice(p2);
return 0;
}
装饰器模式Decorator: 装饰类:主要增加现有类的功能 但是:增加现有类的功能还有一个方法,就是新增加一个子类
|