设计模式6:Composite

Entry.java:

 

package gendwang.cisco.com;



public abstract class Entry 

{

	private int height = 0;

	private String name;

	private Type type;



	public Entry(String name)

	{

		this.name = name;

	}	

	

	public int getHeight() {

		return height;

	}



	public void setHeight(int height) {

		this.height = height;

	}



	public String getName() {

		return name;

	}



	public void setName(String name) {

		this.name = name;

	}



	public Type getType() {

		return type;

	}



	public void setType(Type type) {

		this.type = type;

	}

	

	public abstract void print();

}


File.java:

 

 

package gendwang.cisco.com;



public class File extends Entry

{

	public File(String name)

	{

		super(name);

		setType(Type.File);

	}

	

	public void print()

	{

		int numOfWhiteSpace = getHeight() * 2;

		for(int i = 0; i < numOfWhiteSpace; i++)

		{

			System.out.print(" ");

		}

		

		System.out.println(getName());

	}

}


Directory.java:

 

 

package gendwang.cisco.com;



import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;



public class Directory extends Entry 

{

	private List<Entry> list = new LinkedList<Entry>();

	

	public Directory(String name)

	{

		super(name);

		setType(Type.Directory);

	}

	

	public void addEntry(Entry entry)

	{

		int myHeight = getHeight();

		incrementHeight(entry, myHeight + 1);

		

		list.add(entry);

	}

	

	public List<Entry> getChilden()

	{

		return list;

	}

	

	public void print()

	{

		int numOfWhiteSpace = getHeight() * 2;

		for(int i = 0; i < numOfWhiteSpace; i++)

		{

			System.out.print(" ");

		}

		System.out.println(getName());

		

		Iterator<Entry> itor = list.iterator();

		while(itor.hasNext())

		{

			Entry entry = itor.next();

			entry.print();

		}

	}

	

	private void incrementHeight(Entry entry, int added)

	{

		int height = entry.getHeight();

		entry.setHeight(height + added);

		

		if(entry.getType() == Type.Directory)

		{

			Directory dir = (Directory)entry;

			List<Entry> list = dir.getChilden();

			Iterator<Entry> itor = list.iterator();

			while(itor.hasNext())

			{

				Entry tmp = itor.next();

				incrementHeight(tmp, added);

			}

		}

	}

}


Type.java:

 

 

package gendwang.cisco.com;



public enum Type 

{

	File,

	Directory

}


Test.java:

 

 

package gendwang.cisco.com;



public class Test 

{

	public static void main(String[] args)

	{

		Directory dir1 = new Directory("tmp");

		Entry file1 = new File("hello.jpg");

		Entry file2 = new File("install.log");

		dir1.addEntry(file1);

		dir1.addEntry(file2);

		

		Directory dir2 = new Directory("system");

		

		Directory dir3 = new Directory("windows");

		dir3.addEntry(dir1);

		dir3.addEntry(dir2);

		

		Directory dir4 = new Directory("root");

		Entry file3 = new File("password");

		dir4.addEntry(file3);

		dir4.addEntry(dir3);

		

		dir4.print();

	}

}


 

 

你可能感兴趣的:(设计模式)