2018-04-16
组合模式
abstract class Component {
public abstract void operation();
public void add(Component c) {
throw new UnsupportedOperationException();
}
public void remove(Component c) {
throw new UnsupportedOperationException();
}
public Component getChild(int i) {
throw new UnsupportedOperationException();
}
}
class ConcreteComponent1 extends Component {
public void operation() {
System.out.println("operation of concrete component 1 ");
}
}
class ConcreteComponent2 extends Component {
public void operation() {
System.out.println("operation of concrete component 2 ");
}
}
class ConcreteComponent3 extends Component {
public void operation() {
System.out.println("operation of concrete component 3 ");
}
}
class Composite extends Component {
private ArrayList<Component> children;
public Composite() {
children = new ArrayList<Component>();
}
public void operation() {
for(Component child: children) {
child.operation();
}
}
public void add(Component c) {
children.add(c);
}
public void remove(Component c) {
children.remove(c);
}
public Component getChild(int i) {
return children.get(i);
}
}
public class Client {
public static void main(String[] args) {
Component c1 = new ConcreteComponent1();
Component c2 = new ConcreteComponent2();
Component c3 = new ConcreteComponent3();
Component c = new Composite();
c.add(c1);
c.add(c2);
c.add(c3);
c.operation();
c.remove(c2);
c.operation();
}
}
忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。