您的位置:首页 > 编程语言 > C语言/C++

C语言设计模式:享元模式

2013-02-15 19:25 323 查看
享元模式的目的是在多个类似对象中共享数据:

A flyweight is an object that minimizes memory use by
sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state
can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.

享元模式可以看成是单例模式的变种,不同之处在于后者共享的是对象,而前者共享的是数据。

下面的例子不错:/article/1797627.html

[cpp] view
plaincopy

typedef struct _Font

{

int type;

int sequence;

int gap;

int lineDistance;

void (*operate)(struct _Font* pFont);

}Font;

上面的Font表示了各种Font的模板形式。所以,下面的方法就是定制一个FontFactory的结构。

[cpp] view
plaincopy

typedef struct _FontFactory

{

Font** ppFont;

int number;

int size;

Font* GetFont(struct _FontFactory* pFontFactory, int type, int sequence, int gap, int lineDistance);

}FontFactory;

这里的GetFont即使对当前的Font进行判断,如果Font存在,那么返回;否则创建一个新的Font模式。

[cpp] view
plaincopy

Font* GetFont(struct _FontFactory* pFontFactory, int type, int sequence, int gap, int lineDistance)

{

int index;

Font* pFont;

Font* ppFont;

if(NULL == pFontFactory)

return NULL;

for(index = 0; index < pFontFactory->number; index++)

{

if(type != pFontFactory->ppFont[index]->type)

continue;

if(sequence != pFontFactory->ppFont[index]->sequence)

continue;

if(gap != pFontFactory->ppFont[index]->gap)

continue;

if(lineDistance != pFontFactory->ppFont[index]->lineDistance)

continue;

return pFontFactory->ppFont[index];

}

pFont = (Font*)malloc(sizeof(Font));

assert(NULL != pFont);

pFont->type = type;

pFont->sequence = sequence;

pFont->gap = gap;

pFont->lineDistance = lineDistance;

if(pFontFactory-> number < pFontFactory->size)

{

pFontFactory->ppFont[index] = pFont;

pFontFactory->number ++;

return pFont;

}

ppFont = (Font**)malloc(sizeof(Font*) * pFontFactory->size * 2);

assert(NULL != ppFont);

memmove(ppFont, pFontFacoty->ppFont, pFontFactory->size);

free(pFontFactory->ppFont);

pFontFactory->size *= 2;

pFontFactory->number ++;

ppFontFactory->ppFont = ppFont;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: