将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
public class Composite_Main {
public static void main(String[] args) {
//盘子主盘子
Component plate = new Plate();
//附盘子1
Component plate_1 = new Plate();
//附盘子2
Component plate_2 = new Plate();
//水果1 主盘子上
Component fruit_1 = new Fruit("fruit_1");
//水果2 附盘子1上
Component fruit_2 = new Fruit("fruit_2");
plate_1.add(fruit_2);
plate.add(plate_1);
plate.add(plate_2);
plate.add(fruit_1);
System.out.println(JSON.toJSONString(plate));
}
}
interface Component{
void eat();
boolean add(Component component);
boolean remove(int index);
}
class NoSupportException extends RuntimeException{
public NoSupportException(String message){
super(message);
}
}
@Data
class Fruit implements Component{
private String name;
public Fruit(String name) {
this.name = name;
}
@Override
public void eat() {
System.out.println("吃水果喽...");
}
@Override
public boolean add(Component component) {
throw new NoSupportException("水果没有添加的赋能哦");
}
@Override
public boolean remove(int index) {
throw new NoSupportException("水果没有祛除的赋能哦");
}
}
@Data
class Plate implements Component{
private List<Component> components;
public Plate() {
this.components = new CopyOnWriteArrayList<>();
}
@Override
public void eat() {
throw new NoSupportException("盘子不能吃哦");
}
@Override
public boolean add(Component component) {
if (CollectionUtils.isEmpty(components)){
this.components = new CopyOnWriteArrayList<>();
}
this.components.add(component);
return false;
}
@Override
public boolean remove(int index) {
if (CollectionUtils.isEmpty(components)){
return Boolean.FALSE;
}
components.remove(index);
return Boolean.TRUE;
}
}