装饰模式实现坦克大战(java)

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

当前:装饰模式

需求:坦克大战

创建两种坦克

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

类图

代码

import java.util.ArrayList;
// static 
class Function{
	static void shot(int type) {
		exe("射击:"+type);
	}
	static void run(int type) {
		exe("前进:"+type);
	}
	static void exe(String str) {
		System.out.println(str);
	}
}
class AddFunction extends Function{
	static void nfraredAiming() {
		exe("红外瞄准");
	}
	static void amphibian() {
		exe("水路两栖");
	}
	static void satellitePositioning() {
		exe("卫星定位");
	}
}
interface IFun{
	void exe(int type);
}
class Shot implements IFun{
	static final Shot mShot = new Shot();
	private Shot() {}
	static Shot get() {
		return mShot;
	}
	public void exe(int type) {
		Function.shot(type);
	}
}
class Run implements IFun{
	static final Run mRun = new Run();
	private Run() {}
	static Run get() {
		return mRun;
	}
	public void exe(int type) {
		Function.run(type);
	}
}
// 
interface ITank{
	void exe();
	void add(IFun f);
}
abstract class Tank implements ITank{
	int mType;
	Tank(){
		add(Shot.get());
		add(Run.get());
	}
	ArrayList<IFun> mFun = new ArrayList<IFun>();
	public void add(IFun f) {
		mFun.add(f);
	}
	public void exe() {
		for(IFun f:mFun) {
			f.exe(mType);
		}
	}
}
class B70Tank extends Tank{
	public B70Tank() {
		mType = 70;
	}
}
class B50Tank extends Tank{
	public B50Tank() {
		mType = 50;
	}
}
abstract class Decorator extends Tank{
	public ITank mTank;
	public Decorator(ITank t) {
		mTank = t;
	}
	public void exe() {
		mTank.exe();
		addEce();
	}
	abstract public void addEce();
}
class NfraredAiming extends Decorator{
	public NfraredAiming(ITank t) {
		super(t);
	}
	public void addEce() {
		AddFunction.nfraredAiming();
	}
}
class Amphibian extends Decorator{
	public Amphibian(ITank t) {
		super(t);
	}
	public void addEce() {
		AddFunction.amphibian();
	}
}
class SatellitePositioning extends Decorator{
	public SatellitePositioning(ITank t) {
		super(t);
	}
	public void addEce() {
		AddFunction.satellitePositioning();
	}
}

public class Client {
	public static void main(String[] args) {
		System.out.println("hello world !");
		ITank t70 = new B70Tank();
		t70.exe();
		ITank t50 = new B50Tank();
		t50.exe();
		Decorator d1 = new NfraredAiming(t70);
		d1.exe();
		Decorator d2 = new Amphibian(d1);
		d2.exe();
		Decorator d3 = new SatellitePositioning(d2);
		d3.exe();
	}
}

运行效果

猜你喜欢

转载自blog.csdn.net/xie__jin__cheng/article/details/88872214