設計模式《十二》——享元模式

簡介

用於減少創建對象的數量,實現對象的共享,當對象多的時候可以減少內存佔用和提高性能。

 

角色與職責

  • Flyweight描述一個接口,通過這個接口flyweight可以接受並作用於外部狀態;
  • ConcreteFlyweight實現Flyweight接口,併爲定義了一些內部狀態,ConcreteFlyweight對象必須是可共享的;同時,它所存儲的狀態必須是內部的;即,它必須獨立於ConcreteFlyweight對象的場景;
  • UnsharedConcreteFlyweight並非所有的Flyweight子類都需要被共享。Flyweight接口使共享成爲可能,但它並不強制共享。所以此類可以沒有。
  • FlyweightFactory創建並管理flyweight對象。它需要確保合理地共享flyweight;當用戶請求一個flyweight時,FlyweightFactory對象提供一個已創建的實例,如果請求的實例不存在的情況下,就新創建一個實例;
  • Client維持一個對flyweight的引用;同時,它需要計算或存儲flyweight的外部狀態。

 

實現

#include <iostream>
#include <string>
#include <map>
using namespace std;
// 對應Flyweight
class Person {
public:
    Person(string name, int age) : m_name(name), m_age(age){}
    virtual void printT() = 0;
protected:
    string m_name;
    int m_age;
};
// 對應ConcreteFlyweight
class Teacher : public Person {
public:
    Teacher(string name, int age, string id) :Person(name, age), m_id(id) {}
    virtual void printT() {
        cout << "name:" << m_name << " age:" << m_age << " id:" << m_id << endl;
    }
private:
    string m_id;
};
// 對應FlyweightFactory
class FlyweightTeacherFactory {
public:
    FlyweightTeacherFactory() {
        m_map.clear();
    }
    ~FlyweightTeacherFactory() {
        while (!m_map.empty()) {
            Person* tmp = NULL;
            map<string, Person*>::iterator it = m_map.begin();
            tmp = it->second;
            m_map.erase(it);
            delete tmp;
        }
    }
    Person* getTeacher(string id) {
        map<string, Person*>::iterator it = m_map.find(id);
        if (it == m_map.end()) {
            string t_name;
            int t_age = 0;
            cout << "input teacher name, please!" << endl;
            cin >> t_name;
            cout << "input teacher age, please!" << endl;
            cin >> t_age;
            Person* temp = new Teacher(t_name, t_age, id);
            m_map.insert(pair<string, Person*>(id, temp));
            return temp;
        }
        else {
            return it->second;
        }
    }
private:
    map<string, Person*> m_map;
};
int main(int argc, char* argv[]) {
    Person *p1 = NULL;
    Person *p2 = NULL;
    FlyweightTeacherFactory* fwtf = new FlyweightTeacherFactory;
    p1 = fwtf->getTeacher("001");
    p1->printT();
    p2 = fwtf->getTeacher("001");
    p2->printT();
    cin.get();
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章