类型: 结构型模式
介绍: 一种树形结构。它又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。
目的: 组合模式依据树形结构来组合对象,用来表示部分以及整体层次。
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
//构造函数
public Employee(String name,String dept, int sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList<Employee>();
}
public void add(Employee e) {
subordinates.add(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
public String toString(){
return ("Employee :[ Name : "+ name +", dept : "+ dept + ", salary :"+ salary+" ]");
}
}
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
//打印该组织的所有员工
System.out.println(CEO);
for (Employee headEmployee : CEO.getSubordinates()) {
System.out.println(headEmployee);
for (Employee employee : headEmployee.getSubordinates()) {
System.out.println(employee);
}
}
}
}
public class Container extends Component {
private java.util.List<Component> component = new ArrayList<>();
public Component getComponent(int n) {
try {
return component.get(n);
} catch (IndexOutOfBoundsException z) {
throw new ArrayIndexOutOfBoundsException("No such child: " + n);
}
}
public Component add(Component comp) {
addImpl(comp, null, -1);
return comp;
}
}
public class CompositeCacheManager implements CacheManager, InitializingBean {
private final List<CacheManager> cacheManagers = new ArrayList();
@Nullable
public Cache getCache(String name) {
Iterator var2 = this.cacheManagers.iterator();
Cache cache;
do {
if (!var2.hasNext()) {
return null;
}
CacheManager cacheManager = (CacheManager)var2.next();
cache = cacheManager.getCache(name);
} while(cache == null);
return cache;
}
}
创建型模式
结构型模式
行为型模式