设计模式15:组合模式
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
透明方式与安全方式:
透明方式:
父类包含所有子类的方法,不需要该方法的子类可以选择throw Exception。
优点:各个子类完全一致,可以使用父类接口调用
缺点:子类实现无意义的方法
安全方式:
子类特有的方法,留到具体的子类中再去实现。
优点:子类方法有意义。
缺点:所有子类不再具有相同的接口。
uml:

代码:
Component及其子类:
public abstract class Component {
protected String name;
public Component(String name){
this.name = name;
}
public abstract void add(Component component);
public abstract void delete(Component component);
public abstract void show(int index);
}
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
List<Component> components = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
components.add(component);
}
@Override
public void delete(Component component) {
components.remove(component);
}
@Override
public void show(int index) {
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < index; i++){
stringBuilder.append("-");
}
System.out.println(stringBuilder.toString() + this.name);
for(Component component : components){
component.show(index + 2);
}
}
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println("A leaf could not add component");
}
@Override
public void delete(Component component) {
System.out.println("A leaf could not delete component");
}
@Override
public void show(int index) {
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < index; i++){
stringBuilder.append("-");
}
System.out.println(stringBuilder.toString() + this.name);
}
}
Demo
public class CompositeDemo {
public static void main(String[] args) {
Composite root = new Composite("root");
root.add(new Leaf("leaf1"));
root.add(new Leaf("leaf2"));
Composite composite1 = new Composite("composite1");
composite1.add(new Leaf("leaf3"));
composite1.add(new Leaf("leaf4"));
composite1.add(new Leaf("leaf5"));
root.add(composite1);
Leaf leaf6 = new Leaf("leaf6");
root.add(leaf6);
root.delete(leaf6);
root.show(1);
}
}
浙公网安备 33010602011771号