设计模式一日一练:亨元模式(Flyweight)

来源:互联网 发布:aamtool Mac 编辑:程序博客网 时间:2024/04/27 15:59

    Flyweight模式,运用共享技术有效地支持大量细粒度的对象。在游戏开发中,享元模式的一个典型应用是动态生成位图字体。

class Texture;// flyweightclass Glyph {public:    void Display(int x, int y);    public:    Texture* tex; // 位图纹理    int c;        // 字符    int w;        // 宽    int h;        // 高}// flyweight factoryclass Font {    public:        Glyph* GetGlyph(int c);            private:        std::map<int,Glyph*> glyphs;}Glyph* GetGlyph(int c) {    Glyph* glyph = null;    if (glyphs.Contains(c)) {        glyph = glyphs[c];    }    else {        glyph = new Glyph();        glyph.c = c;        // todo ...  创建位图纹理,设置宽高        glyphs[c] = glyph;    }    return glyph;}// testvoid Test() {    const char* str = "aabccc";    Font* font = new Font();    for (char* ptr = str; *ptr != '\0'; ptr++) {        Glyph* glyph = font->GetGlyph(*ptr);        glyph->Display((ptr - str) * 20, 0);    }        // todo ...  destroy}

    PS. 我的设计模式系列blog,《设计模式》专栏,通过简单的示例演示设计模式,对于初学者很容易理解入门。深入学习请看GoF的《设计模式》。
13 0
原创粉丝点击