组合模式

组合模式将对象以树形结构组织起来,以达成“部分-整体”的层次结构,使得客户端对单个对象和组合对象的使用具有一致性。

 

水果类,相当于Component

package compositedemo;

import java.util.ArrayList;

import java.util.List;

public abstract class Fruit {

protected List<Fruit> children;

public Fruit() {

this.children = new ArrayList<Fruit>();

}

public void add(Fruit fruit) throws UnsupportedOperationException {

throw new UnsupportedOperationException("叶子节点不应调用此方法");

}

public void remove(Fruit fruit) throws UnsupportedOperationException {

throw new UnsupportedOperationException("叶子节点不应调用此方法");

}

public abstract void get();

}

---------------------

苹果类,相当于Composite

package compositedemo;

public class Apple extends Fruit {

@Override

public void add(Fruit fruit) {

// TODO Auto-generated method stub

this.children.add(fruit);

}

@Override

public void remove(Fruit fruit) {

// TODO Auto-generated method stub

this.children.remove(fruit);

}

@Override

public void get() {

// TODO Auto-generated method stub

for (Fruit child : this.children) {

child.get();

}

}

}

-----------------------

香蕉类,相当于Composite

package compositedemo;

public class Banana extends Fruit {

@Override

public void add(Fruit fruit) {

// TODO Auto-generated method stub

this.children.add(fruit);

}

@Override

public void remove(Fruit fruit) {

// TODO Auto-generated method stub

this.children.remove(fruit);

}

@Override

public void get() {

// TODO Auto-generated method stub

for (Fruit child : this.children) {

child.get();

}

}

}

-----------------------

北方苹果类,相当于Leaf,其他具体水果类似

package compositedemo;

public class NorthApple extends Fruit {

@Override

public void get() {

// TODO Auto-generated method stub

System.out.println("NorthApple get");

}

}

-----------------------

测试类,相当于Client

package compositedemo;

public class Client {

public static void main(String[] args) {

 

Fruit apple=new Apple();

Fruit banana=new Banana();

 

Fruit northApple = new NorthApple();

Fruit northBanana = new NorthBanana();

Fruit southApple = new SouthApple();

Fruit southBanana = new SouthBanana();

apple.add(northApple);

// apple.add(southApple);

// banana.add(northBanana);

banana.add(southBanana);

 

System.out.println("组合对象调用功能方法");

apple.get();

banana.get();

 

System.out.println("叶子对象调用功能方法");

northApple.get();

northBanana.get();

southApple.get();

southBanana.get();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值