当前:抽象工厂
需求:坦克大战
创建两种坦克
坦克类型 | 射程 | 速度 |
b70 | 70米 | 时/70公里 |
b50 | 50米 | 时/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);
}
}
运行结果
模式补充说明