変換JAVA(XI)デザインパターンデザインパターンのフライ級

序文

      この章では、知識フライ級のデザインモードを記述する

方法

1.コンセプト

それでもシングルトンデザインパターンが前に学んだ覚えていますか!

シングルトン:クラスのインスタンスを1つだけ確実にするために、グローバルアクセスポイントのインスタンスへのアクセスを提供します

Singletonパターンを採用し、重複するデザインパターンを作成しないように、クラスの条件と複雑さを確保するために作成され、クラス(属性)が固定されています!

しかし、そこにいくつかの比較的一定の財産であり、プロパティの一部は、常に日常生活の一部のオブジェクトの間で変化しています。次のような作品を行きます

何がピースオブジェクトについて、その性質は、比較的、唯一の黒と白の色を固定し、我々はそれの各部分の位置が同じではありません発見しました!

我々は、オブジェクトを作成するためのパターンをフライ級していない場合は、黒のポーンを作成するための光の量が膨大な、と非常にメモリ消費量です。

この問題を解決するために、我々は、フライ級のデザインパターンを導入しました。

デザインパターンのアイデアの実現を楽しむために2元 

1)適切なプロジェクトを作成します

2)フライ級フライ級クラスのインタフェースと実装クラスを作成します。

package flyWeight;

/**
 * 棋子享元接口
 * @author jwang
 *
 */
public interface IChessFlyWeight {

	public String getColor();
	
	public void display(ChessPosition chessPosition);
}

/**
 * 棋子享元类
 * @author jwang
 *
 */
class ChessFlyWeight implements IChessFlyWeight{
	
	private String color;//享元颜色(黑色、白色)

	
	public ChessFlyWeight(String color) {
		super();
		this.color = color;
	}

	@Override
	public String getColor() {
		return this.color;
	}

	@Override
	public void display(ChessPosition chessPosition) {
		System.out.println("棋子的颜色:"+getColor());
		System.out.println("棋子的位置:"+chessPosition.getX()+"---"+chessPosition.getY());
		
	}
	
}

3)非共有の属性クラスを作成します

package flyWeight;

/**
 * 棋子非共享属性
 * @author jwang
 *
 */
public class ChessPosition {
	private int x;
	private int y;
	public ChessPosition(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
	
}

4)クラスファクトリフライ級を作成します。

package flyWeight;

import java.util.HashMap;
import java.util.Map;


/**
 * 享元工厂类
 * @author jwang
 *
 */
public class ChessFlyWeightFactory {

	//key为棋子的颜色
	private static Map<String,IChessFlyWeight> map = new HashMap<>();
	
	public static IChessFlyWeight getChess(String color){
		if(map.get(color)!=null){
			return map.get(color);
		}else {
			IChessFlyWeight chessFlyWeight = new ChessFlyWeight(color);
			map.put(color, chessFlyWeight);
			return chessFlyWeight;
		}
	}
}

5)書き込みテストコードテストします

package flyWeight;

public class Test {

	public static void main(String[] args) {
		IChessFlyWeight chess1 =ChessFlyWeightFactory.getChess("黑色");
		IChessFlyWeight chess2 =ChessFlyWeightFactory.getChess("黑色");
		System.out.println("是否为相同对象:"+(chess1==chess2));
		
		//加入非共享属性
		chess1.display(new ChessPosition(1, 2));
		chess2.display(new ChessPosition(3, 4));
	}
}

次のようにプログラムの実行結果は以下のとおりです。

結論:

 百点の黒の作品の場合、同時にコストのみメモリを節約し、メモリ内のオブジェクトを作成するためにフライ級を使用して作成しました。

しかし、非共有の属性を追加するので、相対的に言ったときに、時間の消費が長くなるように、いわゆる関連するコードを実装する必要性を「宇宙の時間を。」

おすすめ

転載: blog.csdn.net/qq_21046965/article/details/92374202
おすすめ