我有轻量级模式。我有抽象类字形。我有从字形派生的字母类和抽象代码。我有从 Code 派生的 YusciiCode、UniCyrCode 和 UniLatCode。
我的轻量级工厂可以这样完成:
template <class T>
class CodeFactory : public AbstractCodeFactory
{
public:
CodeFactory();
virtual ~CodeFactory();
virtual Glyph* GetFlyweight(unsigned int code);
virtual Glyph* GetFlyweight(string letter);
private:
// pool of flyweights (codes or letters)
map <unsigned int, Glyph*> my_code_map;
map <string, Glyph*> my_letter_map;
};
可以这样做:
template <class key, class T>
class CodeFactory : public AbstractCodeFactory
{
public:
CodeFactory();
virtual ~CodeFactory();
virtual Glyph* GetFlyweight(key code);
private:
// pool of flyweights (codes or letters)
map <key, Glyph*> my_code_map;
};
在第一个示例中,GCC 链接器告诉我没有 Letter(unsigned int) 和 xxxCode(string) 构造函数。实际上没有,而且 GCC 是正确的,但是有没有比定义那些构造函数更好的方法呢?
在seccond ecample GCC编译器告诉我有错误就行了
map <key, Glyph*>::iterator it;
GetFlyweight 函数。
实现这种享元模式的方法是什么?
我需要使用它。这是我当前的实现:
class AbstractCodeFactory
{
public:
AbstractCodeFactory();
virtual ~AbstractCodeFactory();
virtual Glyph* GetFlyweight(unsigned int code) = 0;
virtual Glyph* GetFlyweight(string letter) = 0;
};
template <class T>
class CodeFactory : public AbstractCodeFactory
{
public:
CodeFactory();
virtual ~CodeFactory();
virtual Glyph* GetFlyweight(unsigned int code);
virtual Glyph* GetFlyweight(string letter);
private:
// pool of flyweights (codes or letters)
map <unsigned int, Glyph*> my_code_map;
map <string, Glyph*> my_letter_map;
};
template <class T>
CodeFactory<T>::CodeFactory()
{
// TODO Auto-generated constructor stub
}
template <class T>
CodeFactory<T>::~CodeFactory()
{
// TODO Auto-generated destructor stub
map <unsigned int, Glyph*>::iterator it;
map <string, Glyph*>::iterator l_it;
for (it = my_code_map.begin(); it != my_code_map.end(); ++it)
{
delete it->second;
it->second = NULL;
my_code_map.erase(it);
}
for (l_it = my_letter_map.begin(); l_it != my_letter_map.end(); ++l_it)
{
delete l_it->second;
l_it->second = NULL;
my_letter_map.erase(l_it);
}
}
template <class T>
Glyph* CodeFactory<T>::GetFlyweight(unsigned int code)
{
map <unsigned int, Glyph*>::iterator it;
T *code_class = NULL;
if ((it = my_code_map.find(code)) == my_code_map.end())
{
my_code_map.insert(pair <unsigned int, Glyph*> (code, code_class = new T(code)));
return code_class;
}
else return it->second;
}
template <class T>
Glyph* CodeFactory<T>::GetFlyweight(string letter)
{
map <string, Glyph*>::iterator it;
T *letter_class = NULL;
if ((it = my_letter_map.find(letter)) == my_letter_map.end())
{
my_letter_map.insert(pair <string, Glyph*> (letter, letter_class = new T(letter)));
return letter_class;
}
else return it->second;
}