坦克大战 享元模式(Flyweight Pattern)

目录:一个实例讲完23种设计模式

当前:享元模式

需求:坦克大战

创建两种坦克

坦克类型 射程 速度
b70 70米 时/70公里
b50 50米 时/70公里

类图

坦克大战 享元模式(Flyweight Pattern)_第1张图片

代码

js实现

c++实现

c#实现

java实现

import java.util.HashMap;
///*interface*/////////////////////////////////////
interface Itank{
	void operation();
}
///*abstract*/////////////////////////////////////
abstract class Tank implements Itank{
	Function mShot;
	Function mRun;
	int mSpecification = 0;
	public Tank(Function shot,Function run) {
		this.mShot = shot;
		this.mRun = run;
	}
	public void operation() {
		mShot.operation(mSpecification);
		mRun.operation(mSpecification);
	}
}
///*concrete*/////////////////////////////////////
class Tank70 extends Tank{
	public Tank70(Function shot,Function run) {
		super(shot,run);
		mSpecification = 70;
	}
}
class Tank50 extends Tank{
	public Tank50(Function shot,Function run) {
		super(shot,run);
		mSpecification = 50;
	}
}

class Function{
	public String mStr;
	public String mUnit;
	Function(String str,String unit){
		mStr = str;
		mUnit = unit;
	}
	public void operation(int specification) {
		System.out.println(mStr+specification+mUnit);
	}
};
class ShotFlyweight extends Function{
	public ShotFlyweight() {
		super("发射距离","米");
	}
}
class RunFlyweight extends Function{
	public RunFlyweight() {
		super("速度","公里");
	}
}
class FlyweightFactory{
	HashMap mMaps = new HashMap();
	public Function GetFlyweitht(String key) {
		Function f = mMaps.get(key);
		if(f == null) {
			return createFlyweight(key);
		}else
		{
			return f;
		}
	} 
	public Function createFlyweight(String key) {
		Function f = null;
		if(key == "shot") {
			f = new ShotFlyweight();
		}else {
			f = new RunFlyweight();
		}
		mMaps.put(key, f);
		return f;
	}
}

public class Client {
	public static void main(String[] args) {
		System.out.println("hello worldff !");
		FlyweightFactory flyweithtFactory = new FlyweightFactory();
		Function fshot = flyweithtFactory.GetFlyweitht("shot");
		Function frun = flyweithtFactory.createFlyweight("run");
		Tank70 t7 = new Tank70(fshot,frun);
		t7.operation();
		Function fshot2 = flyweithtFactory.GetFlyweitht("shot");
		Function frun2 = flyweithtFactory.createFlyweight("run");
		Tank50 t5 = new Tank50(fshot2,frun2);
		t5.operation();
		
	}

}

运行结果

你可能感兴趣的:(设计模式-坦克大战-java)