1. 程式人生 > 其它 >【轉】資料庫SQL優化大總結之 百萬級資料庫優化方案

【轉】資料庫SQL優化大總結之 百萬級資料庫優化方案

享元模式

模式所涉及的角色

Flyweight: 享元介面,通過這個介面傳入外部狀態並作用於外部狀態;
ConcreteFlyweight: 具體的享元實現物件,必須是可共享的,需要封裝享元物件的內部狀態;
UnsharedConcreteFlyweight: 非共享的享元實現物件,並不是所有的享元物件都可以共享,非共享的享元物件通常是享元物件的組合物件;
FlyweightFactory: 享元工廠,主要用來建立並管理共享的享元物件,並對外提供訪問共享享元的介面;

這裡列舉非上圖繼承關係但是容易理解

//棋子享元類 棋子的相同的屬性物件。
public class ChessUnit {
	public int id;
	public String color;
	public String chessName;
	
	public ChessUnit (int id, String color, String chessName) {
		this.id = id;
		this.color = color;
		this.chessName = chessName;
	}
}
//真正的棋子類 帶有座標
public class Chess {
	private ChessUnit chessUnit;
	private int x;
	private int y;
	public Chess(ChessUnit chessUnit, int x, int y){
		this.chessUnit = chessUnit;
		this.x = x;
		this.y = y;
	}

}
//提供一個工廠類,儲存不變的那些固定的不變的要被共享的享元物件,用靜態物件儲存
public class ChessUnitFactory {
	
	private static final  Map<Integer, ChessUnit>  chesses = new HashMap<Integer, ChessUnit>();
	
	static {
		chesses.put(1, new ChessUnit(1, "red", "馬"));
		chesses.put(2, new ChessUnit(1, "red", "將"));
		chesses.put(3, new ChessUnit(1, "red", "士"));
		chesses.put(4, new ChessUnit(1, "red", "象"));	
	}
	public static ChessUnit getChessByid(int chessId){
		return chesses.get(chessId);
	}

}
//一個棋盤類,在構造方法中呼叫init方法,利用儲存好的靜態變數來初始化物件,節約記憶體空間。
public class ChessBoard {
	
	private Map<Integer, Chess> chessBoard = new HashMap<Integer, Chess>();
	
	public	ChessBoard(){
		init();
	}
	
	public void init() {
		chessBoard.put(1, new Chess(ChessUnitFactory.getChessByid(1),123,32));
		chessBoard.put(2, new Chess(ChessUnitFactory.getChessByid(2),123,32));
		chessBoard.put(3, new Chess(ChessUnitFactory.getChessByid(3),123,32));
		chessBoard.put(4, new Chess(ChessUnitFactory.getChessByid(4),123,32));
	}
}