定义:运用共享技术,有效的实现支持大量细粒度对象的复用
类图:
举个围棋的例子,围棋的棋盘共有361格,即可放361个棋子。现在要实现一个围棋程序,该怎么办呢?首先要考虑的是棋子棋盘的实现,可以定义一个棋子的类,成员变量包括棋子的颜色、形状、位置等信息,另外再定义一个棋盘的类,成员变量中有个容器,用于存放棋子的对象。下面给出代码表示:
棋子的定义,当然棋子的属性除了颜色和位置,还有其他的,这里略去。这两个属性足以说明问题。
常用场景
1.当系统中有大量的细粒度对象实例,而且这些对象实例中有一些属性是重复的情况下,考虑使用。
文本编辑器,输入法之类的常用应用。
优点
1.提高了系统的效率,减小了内存的消耗。
2.减少了重复代码。
3.减少了系统的复杂度。
缺点
1.维护共享对象和查找所需的共享对象需要花费很多时间,因为共享模式将对象进行了细粒度话,而不是在一个对象中产生。
代码//piece's color
enum PieceColor {BLACK, WHITE};
//position
struct PiecePos
{
int x;
int y;
PiecePos(int a, int b): x(a), y(b) {}
};
//define a piece
class Piece
{
protected:
PieceColor m_color;
PiecePos m_pos;
public:
Piece(PieceColor color, PiecePos pos): m_color(color), m_pos(pos) {}
~Piece() {}
virtual void Draw() {}
};
class BlackPiece: public Piece
{
public:
BlackPiece(PieceColor color, PiecePos pos): Piece(color, pos) {}
~BlackPiece() {}
void Draw() { cout<<" make a black piece"<<endl;}
};
class WhitePiece: public Piece
{
public:
WhitePiece(PieceColor color, PiecePos pos): Piece(color, pos) {}
~WhitePiece() {}
void Draw() { cout<<" make a white piece"<<endl;}
};
class PieceBoard
{
private:
vector<Piece*> m_vecPiece; //The pieces already on board
string m_blackName; //the black name
string m_whiteName; //the white name
public:
PieceBoard(string black, string white): m_blackName(black), m_whiteName(white){}
~PieceBoard() { Clear(); }
void SetPiece(PieceColor color, PiecePos pos) //new a piece to the board
{
Piece * piece = NULL;
if(color == BLACK) //from the black
{
piece = new BlackPiece(color, pos); //new a piece
cout<<m_blackName<<" the position is("<<pos.x<<','<<pos.y<<")";
piece->Draw(); //draw the black piece on board
}
else
{
piece = new WhitePiece(color, pos);
cout<<m_whiteName<<" the position is("<<pos.x<<','<<pos.y<<")";
piece->Draw();
}
m_vecPiece.push_back(piece); //store the piece
}
void Clear() //free the memory
{
int size = m_vecPiece.size();
for(int i = 0; i < size; i++)
delete m_vecPiece[i];
}
};
int main()
{
cout<<"\n--------------start of the main()---------------"<<endl;
PieceBoard pieceBoard("A","B");
pieceBoard.SetPiece(BLACK, PiecePos(4, 4));
pieceBoard.SetPiece(WHITE, PiecePos(4, 16));
pieceBoard.SetPiece(BLACK, PiecePos(16, 4));
pieceBoard.SetPiece(WHITE, PiecePos(16, 16));
cout<<"\n--------------end of the main()---------------"<<endl;
return 0;
}