zoukankan      html  css  js  c++  java
  • 设计模式之享元模式(FlyWeight)

    #include <iostream>
    #include <string>
    #include <list>
    #include <vector>
    using namespace std;
    enum COLOR{WHITE,BLACK};
    
    /************************************************************************/
    /* 装饰模式的作用是为对象增加属性										*/
    /************************************************************************/
    
    struct PiecePos
    {
    	int x;
    	int y;
    	PiecePos(int a,int b):x(a),y(b){}
    };
    
    class Piece
    {
    public:
    	virtual void draw(){}
    };
    class BlackPiece:public Piece
    {
    public:
    	virtual void draw(){cout << " set a black piece"<<endl;}
    };
    class WhitePiece:public Piece
    {
    public:
    	virtual void draw(){cout << " set a white piece"<<endl;}
    };
    
    
    class PieceBoard
    {
    public:
    	PieceBoard(string balckname,string whitename):
    	m_whitename(whitename),m_balckname(balckname),m_blackpiece(NULL),m_whitepiece(NULL)
    	{
    
    	}
    	void SetPiece(COLOR color,PiecePos pos)
    	{
    		if (color == BLACK)
    		{
    			if (NULL == m_blackpiece)
    			{
    				m_blackpiece = new BlackPiece();
    			}
    			cout << m_balckname << " on the pos" << pos.x << " and " << pos.y;
    			m_blackpiece->draw();
    		}
    		else
    		{
    			if (NULL == m_whitepiece)
    			{
    				m_whitepiece = new WhitePiece();
    			}
    			cout << m_whitename << " on the pos" << pos.x << " and " << pos.y;
    			m_whitepiece->draw();
    		}
    		m_vecPos.push_back(pos);
    	}
    private:
    	vector<PiecePos> m_vecPos;
    	Piece *m_blackpiece;
    	Piece *m_whitepiece;
    	string m_balckname;
    	string m_whitename;
    };
    
    
    int main()
    {
    	PieceBoard pieceboard("A","B");
    	pieceboard.SetPiece(WHITE,PiecePos(4,6));	
    	pieceboard.SetPiece(BLACK,PiecePos(3,5));
    	pieceboard.SetPiece(WHITE,PiecePos(2,8));
    	pieceboard.SetPiece(BLACK,PiecePos(1,9));
    	return 0;
    }
    

    享元模式原理:所谓享元模式,是共享一些元数据对象,例如棋盘的棋子,如果我们对每个棋子建立一个对象然后组织成一个容器,则需要很多个对象。可以只建立两个对象,一个黑子对象,一个白子对象,由棋盘共享,棋盘维护一个保存棋子位置的对象。

    代码如下:

  • 相关阅读:
    Web服务器和应用服务器的区别
    Java程序员应该知道的10个调试技巧
    java快捷键个人总结
    MySQL主从复制与读写分离
    CDN(内容分发网络)技术原理
    淘宝技术发展
    Monitor a Folder using Java
    Android eclipse中程序调试
    在学校教学Java是有争议的
    LINUX ubuntu 12.04 svn 1.6.7 苦逼的装了一个下午啊!! 绝对详细!正确!不吭爹!!
  • 原文地址:https://www.cnblogs.com/liuweilinlin/p/3205195.html
Copyright © 2011-2022 走看看