design_patterns/13_proxy.cpp
Yuki f00a7d284e
feat: Proxy
Implemented a demo for the Proxy.
2025-05-04 22:50:23 +08:00

64 lines
1.3 KiB
C++

#include <iostream>
#include <memory>
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<RawService> rs;
const string role;
public:
UserServiceProxy(const string& s) : role(s) {
rs = make_shared<RawService>();
}
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();
}