目录
1. 享元模式简介
2. 代码示例
1. 享元模式简介
享元模式是一种结构型模式。
享元模式用于缓存共享对象,降低内存消耗。共享对象相同的部分,避免创建大量相同的对象,减少内存占用。
享元模式需要将对象分成内部状态和外部状态两个部分。
所谓内部状态指的是可以共享的状态,外部状态指的是会随着对象的使用而改变的的状态。
比如,如果要模拟一个五子棋程序。对棋子来说,棋子的图片就属于内部状态,而棋子的位置和大小就属于外部状态。棋子的图片可以被所有使用棋子的地方所共享,棋子的位置和大小每个使用的地方都不一样。
享元模式通常要搭配简单工厂模式一起使用,在简单工厂内使用一个享元对象的缓存池,缓存享元对象。
2. 代码示例
就以棋子模拟程序作为示例,代码如下所示:
#if 1#include <iostream>
#include <map>
#include <memory>
#include <string>using namespace std;enum ChessPieceType { White, Black };class ChessPiece {
public:virtual void Draw(int x, int y) = 0;virtual ~ChessPiece() {}
};class WhiteChessPiece : public ChessPiece
{
public:void Draw(int x, int y) override{cout << "在(" << x << "," << y << ") 位置放置白棋子" << endl;}
};class BlackChessPiece : public ChessPiece
{
public:void Draw(int x, int y) override{cout << "在(" << x << "," << y << ") 位置放置黑棋子" << endl;}
};class ChessFactory
{
public:static shared_ptr<ChessPiece> CreateChessPiece(ChessPieceType type){if (chessPieces.find(type) == chessPieces.end()){if (type == White){chessPieces[type] = make_shared<WhiteChessPiece>();}else if (type == Black){chessPieces[type] = make_shared<BlackChessPiece>();}}return chessPieces[type];}
private:static map<ChessPieceType, shared_ptr<ChessPiece>> chessPieces;
};map<ChessPieceType, shared_ptr<ChessPiece>> ChessFactory::chessPieces;int main()
{auto piece1 = ChessFactory::CreateChessPiece(ChessPieceType::White);piece1->Draw(1, 2);auto piece2 = ChessFactory::CreateChessPiece(ChessPieceType::Black);piece2->Draw(3, 4);auto piece3 = ChessFactory::CreateChessPiece(ChessPieceType::White);piece3->Draw(5, 6);return 0;
}#endif
运行截图如下: