반응형
proxy pattern
1. case 1
#include <iostream> #include <string> using namespace std; class Person { public: string nameString; static string list[]; static int next; public: Person() { nameString = list[next++]; } string name() { return nameString; } }; string Person::list[] = { "Tom", "Dick", "Harry", "Bubba" }; int Person::next = 0; class PettyCashProtected { public: int balance; public: PettyCashProtected() { balance = 500; } bool withdraw(int amount) { if (amount > balance) { return false; } balance -= amount; return true; } int getBalance() { return balance; } }; class PettyCash { public: PettyCashProtected realThing; public: bool withdraw(Person &p, int amount) { if (p.name() == "Tom" || p.name() == "Harry" || p.name() == "Bubba") { return realThing.withdraw(amount); } else { return false; } } int getBalance() { return realThing.getBalance(); } }; int main() { PettyCash pc; Person workers[4]; for (int i = 0, amount = 100; i < 4; i++, amount += 100) { if (!pc.withdraw(workers[i], amount)) cout << "No money for " << workers[i].name() << '\n'; else cout << amount << " dollars for " << workers[i].name() << '\n'; } cout << "Remaining balance is " << pc.getBalance() << '\n'; }
결과
g++ -o proxy proxy.cpp hacker@HACKER:~/cpp$ ./proxy 100 dollars for Tom No money for Dick 300 dollars for Harry No money for Bubba Remaining balance is 100
2. case 2
#include <string> #include <iostream> using namespace std; class Subject { public: virtual void execute() = 0; }; class RealSubject: public Subject { public: string str; public: RealSubject(string s) { str = s; } /*virtual*/void execute() { cout << str << '\n'; } }; class ProxySubject: public Subject { public: string first, second, third; RealSubject *ptr; public: ProxySubject(string s) { int num = s.find_first_of(' '); first = s.substr(0, num); s = s.substr(num + 1); num = s.find_first_of(' '); second = s.substr(0, num); s = s.substr(num + 1); num = s.find_first_of(' '); third = s.substr(0, num); s = s.substr(num + 1); ptr = new RealSubject(s); } ~ProxySubject() { delete ptr; } RealSubject *operator->() { cout << first << ' ' << second << ' '; return ptr; } /*virtual*/void execute() { cout << first << ' ' << third << ' '; ptr->execute(); } }; int main() { ProxySubject obj(string("the quick brown fox jumped over the dog")); obj->execute(); obj.execute(); }
결과
hacker@HACKER:~/cpp$ g++ -o p3 p3.cpp hacker@HACKER:~/cpp$ ./p3 the quick fox jumped over the dog the brown fox jumped over the dog
반응형
'C++ > 0x01-design pattern' 카테고리의 다른 글
Factory Method (0) | 2016.07.18 |
---|---|
builder pattern (0) | 2016.07.18 |
Flyweight pattern (0) | 2016.07.18 |
facade pattern (0) | 2016.07.14 |
decorator pattern. (0) | 2016.07.14 |