组合模式测试组合模式(Composite Pattern)
改章节是一篇关于组合模式测试的帖子
像一个树形结构一样使用基本的对象和自己本身构建一个复杂的对象,称为组合模式。 这类模式很轻易学习以及应用到某个系统中。组合模式属于结构设计模式之一,比拟常用。经典的UML图如下:
一个简单的实例程序来说明组合模式是如何实现的。定义一个Employee类,充任组合模式中的表演者,CompositePatternDemo作为测试类。
public class Employee { private String name; private String dept; private int salary; private List<Employee> subordinates; // constructor public Employee(String name,String dept, int sal) { this.name = name; this.dept = dept; this.salary = salary; 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); //print all employees of the organization System.out.println(CEO); for (Employee headEmployee : CEO.getSubordinates()) { System.out.println(headEmployee); for (Employee employee : headEmployee.getSubordinates()) { System.out.println(employee); } } } }
测试结果:
Employee :[ Name : John, dept : CEO, salary :0 ] Employee :[ Name : Robert, dept : Head Sales, salary :0 ] Employee :[ Name : Richard, dept : Sales, salary :0 ] Employee :[ Name : Rob, dept : Sales, salary :0 ] Employee :[ Name : Michel, dept : Head Marketing, salary :0 ] Employee :[ Name : Laura, dept : Marketing, salary :0 ] Employee :[ Name : Bob, dept : Marketing, salary :0 ]
文章结束给大家分享下程序员的一些笑话语录:
程序员的愿望
有一天一个程序员见到了上帝.上帝: 小伙子,我可以满足你一个愿望.程序员: 我希望中国国家队能再次打进世界杯.
上帝: 这个啊!这个不好办啊,你还说下一个吧!
程序员: 那好!我的下一个愿望是每天都能休息6个小时以上.
上帝: 还是让中国国家打进世界杯.