组合模式将对象以树形结构组织起来,以达成“部分-整体”的层次结构,使得客户端对单个对象和组合对象的使用具有一致性。
水果类,相当于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();
}
}