#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
enum Color {WHITE, BLACK, GRAY};
struct Position
{
int cx;
int cy;
};
bool cmp(const Position& Fist, const Position& Second)
{
if(Fist.cx == Second.cx)
{
return Fist.cy < Second.cy;
}
else
{
return Fist.cx < Second.cx;
}
}
class Pieces
{
protected:
string m_strColor;//
Position m_Pos;//
//Color m_color;
public:
Pieces(string strColor):m_strColor(strColor) {}
virtual void SetPos(int x, int y) = 0;
virtual string GetColor() const = 0;
};
class FuckPieces:public Pieces
{
public:
FuckPieces(string strColor):Pieces(strColor) {}
void SetPos(int x, int y);
void GetAllPos();
string GetColor() const;
private:
vector<Position> m_vecPos;
};
void FuckPieces::SetPos(int x, int y)
{
m_Pos.cx = x;// 其实m_Pos没有必要,,因为会存到vector中
m_Pos.cy = y;
//vector<Position>::const_iterator it = m_vecPos
m_vecPos.push_back(m_Pos);//暂时没有必要去重
}
string FuckPieces::GetColor() const
{
return m_strColor;
}
void FuckPieces::GetAllPos()
{
vector<Position>::const_iterator it = m_vecPos.begin();
cout<<GetColor()<<"'s position are :"<<endl;
sort(m_vecPos.begin(), m_vecPos.end(), cmp);
while(it != m_vecPos.end())
{
cout<<"("<<(*it).cx<<", "<<(*it).cy<<")"<<endl;
++it;
}
}
class ChessBoard
{
public:
Pieces* GetPiece(char* strName);
void GetAllPiecePos() const;
private:
map<string, Pieces*> m_PiecesMap;
};
void ChessBoard::GetAllPiecePos() const
{
map<string, Pieces*>::const_iterator it = m_PiecesMap.begin();
while(it != m_PiecesMap.end())
{
dynamic_cast<FuckPieces*>(it->second)->GetAllPos();
cout<<endl;
++it;
}
}
Pieces* ChessBoard::GetPiece(char* strTemp)
{
string strName = strTemp;
map<string, Pieces*>::const_iterator it = m_PiecesMap.find(strName);
if (it != m_PiecesMap.end())
{
return it->second;
}
else
{
Pieces* pPieces = new FuckPieces(strName);
//m_PiecesMap[strName] = pPieces;
m_PiecesMap.insert(make_pair(strName, pPieces));
return pPieces;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
ChessBoard* pBoard = new ChessBoard;
Pieces* pPieces = pBoard->GetPiece("black");
pPieces->SetPos(3,6);
pPieces->SetPos(2,8);
pPieces = pBoard->GetPiece("fuck the Life");
pPieces->SetPos(22,6);
pPieces->SetPos(4,8);
pBoard->GetAllPiecePos();
//dynamic_cast<FuckPieces*>(pPieces)->GetAllPos();
getchar();
return 0;
}
c++享元模式
最新推荐文章于 2023-04-06 16:02:10 发布