GoF Definition:
Compose objects into tree structures to represent part-whole hierarchies. The composite pattern lets clients treat individual objects and compositions of objects uniformly.
概念
组合模式,将对象组合成树形结构以表示部分-整体 的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
例子
任何树型数据结构都符合组合模式。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
public interface { public String getDetails () ; } public class Teacher implements { private String teacherName; private String deptName; private List<ITeacher> controls; Teacher(String teacherName, String deptName) { this .teacherName = teacherName; this .deptName = deptName; controls = new ArrayList<>(); } public void add (Teacher teacher) { controls.add(teacher); } public void remove (Teacher teacher) { controls.remove(teacher); } public List<ITeacher> getControllingDepts () { return controls; } public String getDetails () { return teacherName + " is the " + deptName; } }
近期评论