代理模式感觉也是套一层壳。
适配器模式主要关注于解决接口的不兼容性问题,而代理模式主要关注于控制对其它对象的访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| class ThirdPartyYouTubeLib { public: virtual std::vector<Video> listVideos() const = 0; virtual Video getVideoInfo(int videoId) const = 0; virtual void downloadVideo(int videoId) const = 0; }
class ThirdPartyYouTubeClass: public ThirdPartyYouTubeLib { public: std::vector<Video> listVideos() { }
Video getVideoInfo(int videoId) { }
void downloadVideo(int videoId) { } }
class CachedYouTubeClass: public ThirdPartyYouTubeLib { private: ThirdPartyYouTubeLib* service; std::vector<Video>* listCache; Video* videoCache; public: bool needReset;
CachedYouTubeClass(ThirdPartyYouTubeLib* service): service(service), needReset(false), listCache(nullptr), videoCache(nullptr) { if (!service) { throw std::invalid_argument("service cannot be nullptr"); } } ~CachedYouTubeClass() { delete listCache; }
std::vector<Video> listVideos() { std::vector<Video> videos; if (listCache == nullptr || needReset) { delete listCache; listCache = new std::vector<Video>; videos = service->listVideos(); for (int i = 0; i < videos.size(); i++) listCache->push_back(videos[i]); } else { for (int i = 0; i < listCache->size(); i++) videos.push_back(*listCache[i]); } return videos; }
Video getVideoInfo(int id) { if (videoCache == nullptr || needReset) { delete videoCache; } Video newVideo = service->getVideoInfo(id) videoCache = new Video(newVideo); return *videoCache; }
void downloadVideo(int id) { if (!videoExists(id) || needReset) service->downloadVideo(id); } }
|