#include <iostream>
#include <list>
#include <map>
using namespace std;
enum class EnumColor
{
Black,
White
};
struct Position
{
int m_x;
int m_y;
Position(int tmpx, int tmpy) :m_x(tmpx), m_y(tmpy) {}
};
class Piece
{
public:
Piece(EnumColor tmpcolor, Position tmppos) :m_color(tmpcolor), m_pos(tmppos){}
void draw()
{
if(m_color == EnumColor::Black)
{
cout << "在位置:(" << m_pos.m_x << "," << m_pos.m_y << ")处绘制了一个黑色棋子!" << endl;
}
else
{
cout << "在位置:(" << m_pos.m_x << "," << m_pos.m_y << ")处绘制了一个白色棋子!" << endl;
}
}
private:
EnumColor m_color;
Position m_pos;
};
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Piece* p_piece1 = new Piece(EnumColor::Black, Position(3, 3));
p_piece1->draw();
Piece* p_piece2 = new Piece(EnumColor::White, Position(5, 5));
p_piece2->draw();
Piece* p_piece3 = new Piece(EnumColor::Black, Position(4, 6));
p_piece3->draw();
Piece* p_piece4 = new Piece(EnumColor::White, Position(5, 7));
p_piece4->draw();
delete p_piece1;
delete p_piece2;
delete p_piece3;
delete p_piece4;
return 0;
}
对于上面的例程来说,棋子的类型无非就是两种,黑和白,在实际的下棋过程当中,只有位置是不一样的,但是却衍生出了多个具有相似度的对象,我们能否进行改造一下,比如,对象只有两个,黑和白,在实际的运转的时候,改变他们的位置就可以了,这样就不用new很多给相似的对象出来了。下面我们进行改造一下。引入享元模式。
#include <iostream>
#include <list>
#include <map>
using namespace std;
enum EnumColor
{
Black,
White
};
struct Position
{
int m_x;
int m_y;
Position(int tmpx, int tmpy) :m_x(tmpx), m_y(tmpy) {}
};
class Piece
{
public:
virtual ~Piece() {}
public:
virtual void draw(Position tmppos) = 0;
};
class BlackPiece :public Piece
{
public:
virtual void draw(Position tmppos)
{
cout << "在位置:(" << tmppos.m_x << "," << tmppos.m_y << ")处绘制了一个黑色棋子!" << endl;
}
};
class WhitePiece :public Piece
{
public:
virtual void draw(Position tmppos)
{
cout << "在位置:(" << tmppos.m_x << "," << tmppos.m_y << ")处绘制了一个白色棋子!" << endl;
}
};
class pieceFactory
{
public:
virtual ~pieceFactory()
{
for(auto iter = m_FlyWeightMap.begin(); iter != m_FlyWeightMap.end(); ++iter)
{
Piece* tmpfw = iter->second;
delete tmpfw;
}
m_FlyWeightMap.clear();
}
Piece* getFlyWeight(EnumColor tmpcolor)
{
auto iter = m_FlyWeightMap.find(tmpcolor);
if(iter == m_FlyWeightMap.end())
{
Piece* tmpfw = nullptr;
if(tmpcolor == Black)
{
tmpfw = new BlackPiece();
}
else
{
tmpfw = new WhitePiece();
}
m_FlyWeightMap.insert(make_pair(tmpcolor, tmpfw));
return tmpfw;
}
else
{
return iter->second;
}
}
private:
std::map<EnumColor, Piece*> m_FlyWeightMap;
};
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
pieceFactory* pfactory = new pieceFactory();
Piece* p_piece1 = pfactory->getFlyWeight(Black);
p_piece1->draw(Position(3, 3));
Piece* p_piece2 = pfactory->getFlyWeight(White);
p_piece2->draw(Position(5, 5));
Piece* p_piece3 = pfactory->getFlyWeight(Black);
p_piece3->draw(Position(4, 6));
Piece* p_piece4 = pfactory->getFlyWeight(White);
p_piece4->draw(Position(5, 7));
delete pfactory;
return 0;
}
|