FlyweightPattern.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. class Flyweight {
  6. public:
  7. Flyweight(string state):_state(state) {
  8. }
  9. virtual void Operation(const string&state) { }
  10. string GetState()const { return _state; }
  11. virtual ~Flyweight() { }
  12. private:
  13. string _state;
  14. };
  15. class ConcreteFlyweight :public Flyweight {
  16. public:
  17. ConcreteFlyweight(string state)
  18. :Flyweight(state) {
  19. cout << "ConcreteFlyweight Build..." << state << endl;
  20. }
  21. void Operation(const string& state) {
  22. cout << "ConcreteFlyweight " << GetState() << " \ " << state << endl;
  23. }
  24. };
  25. class FlyweightFactory {
  26. public:
  27. Flyweight *GetFlyweight(std::string key) {
  28. for (auto fly : _flys) {
  29. if (fly->GetState() == key) {
  30. cout << "already created by users..." << endl;
  31. return fly;
  32. }
  33. }
  34. Flyweight *fn = new ConcreteFlyweight(key);
  35. _flys.push_back(fn);
  36. return fn;
  37. }
  38. private:
  39. std::vector<Flyweight*> _flys;
  40. };
  41. int main() {
  42. FlyweightFactory *fc = new FlyweightFactory();
  43. Flyweight *fw1 = fc->GetFlyweight("hello");
  44. Flyweight *fw2 = fc->GetFlyweight("world");
  45. Flyweight *fw3 = fc->GetFlyweight("hello");
  46. delete fw1;
  47. delete fw2;
  48. //delete fw3;
  49. delete fc;
  50. return 0;
  51. }