设计模式之——代理模式

it2022-05-05  177

IGiveGift.h

#ifndef IGIVEGIFT_H #define IGIVEGIFT_H class IGiveGift { public: IGiveGift() {} virtual void giveDolls() = 0; }; #endif // IGIVEGIFT_H

pursuit.h

#ifndef PURSUIT_H #define PURSUIT_H #include <QString> #include "IGiveGift.h" class Pursuit : public IGiveGift { QString m_name; public: Pursuit(QString name) { this->m_name = name; } void giveDolls() { qDebug() << m_name << " 送你洋娃娃"; } }; #endif // PURSUIT_H

proxy.h

#ifndef PROXY_H #define PROXY_H #include <QString> #include "IGiveGift.h" #include "pursuit.h" class Proxy : public IGiveGift { public: Proxy(QString name) { m_gg = new Pursuit(name); } void giveDolls() { m_gg->giveDolls(); } private: Pursuit *m_gg; }; #endif // PROXY_H

main

#include <QApplication> #include <QtDebug> #include "proxy.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Proxy *proxy = new Proxy("小明"); proxy->giveDolls(); return a.exec(); }

真是对象(Pursuit)、代理对象(proxy)同时继承一个接口(IGiveGift)。真实对象实现接口方法。代理对象中定义真实对象,接口方法中调用真实对象的方法。从而实现对真实对象方法的封装

UML


最新回复(0)