c++ 实现享元模式发生链接错误~

想开了,不卷了 2017-12-25 11:49:39
#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;
}
...全文
393 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
是不是单例模式只有在设计操作系统的时候才用得到?
  • 打赏
  • 举报
回复
老师,您这句话,我不理解...,您可以详细说一下吗?
赵4老师 2017-12-25
  • 打赏
  • 举报
回复
离开操作系统,不谈单例模式。
代码运输员 2017-12-25
  • 打赏
  • 举报
回复
享元工厂是个单例模式,所以它的其他成员变量不需要是静态变量了,否则构造函数中会调用一个没有定义的变量. class IgoChessmanFactory { private: 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; } IgoChessman* getIgoChessman(string color) { return (IgoChessman*)jihe->find(color)->second; } }; 如果遇到必须用静态变量的情况,可以在类外定义,必须这样 class IgoChessmanFactory { private: static map<string, IgoChessman*>*jihe; //享元池 .... }; map<string, IgoChessman*>* IgoChessmanFactory::jihe = new map<string, IgoChessman*>(); 当然单例模式最好不要再生成其他静态变量
wodexiaojidan 2017-12-25
  • 打赏
  • 举报
回复
静态成员变量都只能用列表初始化;显然你这个用观察者模式更好。。。

5,530

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 模式及实现
社区管理员
  • 模式及实现社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧