#include #include using namespace std; class Service { public: virtual int read() = 0; virtual int write() = 0; virtual ~Service() = default; }; class RawService : public Service { public: virtual int read() override { cout << "read succeed" << endl; return 1; } virtual int write() override { cout << "write succeed" << endl; return 1; } }; // Inherit from the same interface to so that the proxy class // and the target class can be used in the same way. class UserServiceProxy : public Service { // Use pointers instead of inheritance to reduce coupling. shared_ptr rs; const string role; public: UserServiceProxy(const string& s) : role(s) { rs = make_shared(); } virtual int read() override { return rs->read(); } virtual int write() override { // Implement peripheral logic here, separating it from the core logic. if (role != "admin") { cout << "write failed: permission denied" << endl; return 0; } return rs->write(); } }; int main() { UserServiceProxy admin("admin"); admin.read(); admin.write(); UserServiceProxy user("user"); user.read(); user.write(); }