当前:组合模式
需求:坦克大战
创建两种坦克
坦克类型 | 射程 | 速度 |
b70 | 70米 | 时/70公里 |
b50 | 50米 | 时/70公里 |
需求补充:增加一个瞄准机能
类图
标准类图连接
坦克大战实现类图
代码
java实现
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);
}
}
运行结果
补充说明
英语
component
adj. 组成的,构成的; n. 成分; 组件; [电子] 元件
operation
n. 操作; 经营; [外科] 手术; [数][计] 运算
leaf
n. 叶子; (书籍等的)一张; 扇页; vi. 生叶; 翻书页; vt. 翻…的页,匆匆翻阅;
composite
n. 复合材料; 合成物; 菊科; adj. 复合的; 合成的; 菊科的; vt. 使合成; 使混合