c++ 实现享元模式发生链接错误~
#include <iostream>
#include <string>
#include<map>
using namespace std;
class IgoChessman //抽象的享元类.
{
public:
virtual string getcolor() = 0;
void display()
{
cout << "棋子的颜色是" << this->getcolor() << endl;
}
};
class Black :public IgoChessman
{
public:
string getcolor()
{
return "black";
}
};
class White :public IgoChessman
{
public:
string getcolor()
{
return "white";
}
};
class Red :public IgoChessman
{
public:
string getcolor()
{
return "Red -Unshare";
}
};
class IgoChessmanFactory
{
private:
static map<string, IgoChessman*>*jihe; //享元池
static IgoChessmanFactory*instance; //单例
IgoChessmanFactory()
{
jihe = new map<string, IgoChessman*>();
IgoChessman *black, *white;
black = new Black();
white = new White();
jihe->emplace("black", black);
jihe->emplace("white", white);
}
public:
static IgoChessmanFactory * getInstance()
{
if (instance == nullptr)
{
instance = new IgoChessmanFactory();
}
return instance;
}
static IgoChessman* getIgoChessman(string color)
{
return (IgoChessman*)jihe->find(color)->second;
}
};
IgoChessmanFactory* IgoChessmanFactory::instance = nullptr;
int main()
{
IgoChessman*black1, *black2, *white1, *white2, *red;
IgoChessmanFactory*factory;
factory = IgoChessmanFactory::getInstance();
//通过享元工厂,获得2个黑色,白色棋子
black1 = factory->getIgoChessman("black");
black2 = factory->getIgoChessman("black");
white1 = factory->getIgoChessman("white");
white2 = factory->getIgoChessman("white");
black1->display();
black2->display();
white1->display();
white2->display();
//非共享,获得一个红色棋子:
red = new Red();
red->display();
system("pause");
return 0;
}