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

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

当前:装饰模式

需求:坦克大战

创建两种坦克

坦克类型射程速度
b7070米时/70公里
b5050米时/70公里

类图

最简单的装模式

代码

js代码

c++代码

c#代码

java代码

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();
	}
}

运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值