java实现Composite(组合)模式

组合模式涉及的是一组对象,其中一些对象可能含有其他对象,这些对象也可以含有对象,因此,有些对象代表的是对象群组。
Composite模式的设计意图在于:让所有的用户能够用统一的接口处理单个对象以及对象群组
package app.composite;

import java.util.ArrayList;
import java.util.Iterator;
/**
 * 类的作用:存在年级和学校,都实现People接口,有输出名字的功能,实现组合模式
 * 调用School的getName();获取全校学生的名字
 * @author Administrator
 *
 */
public class CompositeTest {
	public static void main(String[] args) {
		School school=new School("前途小学");
		Grade grade1=new Grade("一年级");
		grade1.add(new Student("小明"));
		grade1.add(new Student("小红"));
		Grade grade2=new Grade("二年级");
		grade2.add(new Student("小亮"));
		grade2.add(new Student("小华"));
		school.add(grade1);
		school.add(grade2);
		school.getName();
	}
}
//学校
interface People{
	public void getName();//获得
}
class Student implements People{
	String name;
	public Student(String name){
		this.name=name;
	}
	@Override
	public void getName() {
		System.out.println(this.name);
	}
}
class Grade implements People{//年级
	private String gradeName; //年级名字
	public Grade(String name){
		this.gradeName=name;
	}
    private ArrayList studentList =new ArrayList(); 
	public void add(Student s){
		this.studentList.add(s);
	}
	@Override
	public void getName() {
		System.out.println("年级:"+this.gradeName);
		Iterator it=studentList.iterator();
		while(it.hasNext()){
			Student student=(Student)it.next();
			student.getName();
		}
		System.out.println();
	}
}
class School implements People{
	public String schoolName;
	public School (String name){
		this.schoolName=name;
	}
	private ArrayList gradeList =new ArrayList(); 
	public void add(Grade g){
		this.gradeList.add(g);
	}
	@Override
	public void getName() {
		System.out.println("学校:"+this.schoolName);
		Iterator it=gradeList.iterator();
		while(it.hasNext()){
			Grade g=(Grade)it.next();
			g.getName();
		}
	}
	
}

 运行结果

学校:前途小学
年级:一年级
小明
小红

年级:二年级
小亮
小华
原文地址:https://www.cnblogs.com/lzzhuany/p/4896265.html