访问者模式坦克大战实现

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

当前:抽象工厂

需求:坦克大战

创建两种坦克

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

类图

代码

interface IVisitor{
	void visitConcreteTank(ITank t);
	void execute(int type);
}
interface ITank{
	int getType();
	void execute(IVisitor v);
}

abstract class Visitor implements IVisitor{
	String mFunction;
	public void visitConcreteTank(ITank t) {
		execute(t.getType());
	}
	public void execute(int type) {
		System.out.println(mFunction+type);
	}
}

class ShotVisitor extends Visitor{
	public ShotVisitor() {
		mFunction = "射击";
	}
}
class RunVisitor extends Visitor{
	public RunVisitor() {
		mFunction = "跑";
	}
}
abstract class Tank implements ITank{
	int mType;
	public int getType() {
		return mType;
	}
	public void execute(IVisitor v) {
		v.visitConcreteTank(this);
	}
}
class B70Tank extends Tank{
	public B70Tank() {
		mType = 70;
	}
}
class B50Tank extends Tank{
	public B50Tank() {
		mType = 50;
	}
}

public class Client {
	public static void main(String[] args) {
		System.out.println("hello world !");
		ITank b7 = new B70Tank();
		ShotVisitor s = new ShotVisitor();
		RunVisitor r = new RunVisitor();
		b7.execute(s);
		b7.execute(r);
		ITank b5 = new B50Tank();
		b5.execute(s);
		b5.execute(r);
	}
}

运行结果

模式补充说明

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值