组合模式坦克大战实现

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

需求:坦克大战

创建两种坦克

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

需求补充:增加一个瞄准机能

类图

标准类图连接

坦克大战实现类图

代码

import java.util.ArrayList;
class Function{
	public String mStr;
	Function(String str){
		mStr = str;
		exe();
	}
	public void exe() {
		System.out.println(mStr);
	}
};

/*
Component 零件
Leaf 叶
Composite 综合
operation 作业
add 追加
remove 移除
getChiled 取得子控件
*/
///* interface */////////////////////////////////////////////
interface IComponent{
	void add(IComponent component);
	void remove(IComponent component);
	void operation();
}
///* interface */////////////////////////////////////////////
abstract class Leaf implements IComponent{
	public void add(IComponent component) {}
	public void remove(IComponent component) {}
}
class ShotTank extends Leaf{
	public void operation() {
		new Function("发射");
	}
}
class RunTank extends Leaf{
	public void operation() {
		new Function("移动");
	}
}
// 瞄准
class AimTank extends Leaf{
	public void operation() {
		new Function("移动");
	}
}

class Composite implements IComponent{
	ArrayList<IComponent> mChiledList = new ArrayList<IComponent>();
	public void add(IComponent component) {
		mChiledList.add(component);
	}
	public void remove(IComponent component) {
		mChiledList.remove(component);
	}
	public void operation() {
		for(IComponent c :mChiledList) {
			c.operation();
		}
	}
}
public class Client {
	public static void main(String[] args) {
		System.out.println("hello worldff !");
		System.out.println("单作业运行");
		ShotTank shot = new ShotTank();
		shot.operation();
		RunTank run = new RunTank();
		run.operation();
		AimTank aim = new AimTank();
		aim.operation();
		System.out.println("组合作业运行:1");
		Composite composite1 = new Composite();
		composite1.add(aim);
		composite1.add(shot);
		System.out.println("组合作业运行:2");
		Composite composite2 = new Composite();
		composite2.add(composite1);
		composite2.add(run);
		
		
	}
}

运行结果

补充说明

猜你喜欢

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