现在的位置: 首页 > 综合 > 正文

设计模式之迭代模式和合成模式(4)

2018年03月18日 ⁄ 综合 ⁄ 共 1933字 ⁄ 字号 评论关闭

    迭代模式和合成模式在Head First Design Patterns(点击下载) 的第9章Well-Mangaed Collections

1 迭代模式 Iterator Pattern

       迭代模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起形成的总体称之为聚集,聚集对象是能够包容一组对象的容器对象。迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。迭代子模式简化了聚集的界面。每一个聚集对象都可以有一个或一个以上的迭代子对象,每一个迭代子的迭代状态可以是彼此独立的。迭代算法可以独立于聚集角色变化。

       迭代模式在Head First Design Patterns一书是这么定义的:The Iterator Pattern provides a way to access the elements of an collection(aggregate) object sequentially

without exposing its underlying representation.

      迭代模式的各部分结构如下图:


      JAVA中集合框架中的Iterator接口就用了这种模式,以用来遍历集合中的元素而没有暴漏具体使用了哪个集合(如HashMap, HashSet)。下面的Student类继承了Iterable接口用于返回一个Iterator,而StudentIterator继承了Iterator接口,详细代码如下:

Student类

public class Student implements Iterable<String> {
	
	static final int MAX_ITEMS=6;
	int numberOfItems=0;
	String[] items;
	
	
	public 	Student(String[] items){
		this.items=items;
	}

	public Iterator<String> iterator() {
		return new StudentIterator(items);
	}
}

StudentIterator类

public class StudentIterator implements Iterator<String> {
	
	private String[] items;
	private int position=0;
	
	public StudentIterator(String[] items){
		this.items=items;
	}

	public boolean hasNext() {
		if(position>=items.length && items[position]==null)
		return false;
		else
			return true;
	}

	public String next() {
		return items[position++];
	}

	public void remove() {
		
//		throw new UnsupportedOperationException();  //if don't want to implement remove method, throw thsi  exception
		
		if(position <=0)
			throw new IllegalStateException("You can't remove an item until you've done at least one next()");
		if(items[position-1]!=null){
			for(int i=position-1;i<(items.length-1);i++)
				items[i]=items[i+1];
		}//end if	
	} //end remove
}

2 合成模式 Composite Pattern

      合成模式:合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。

     合成模式在Head First Design Patterns一书是这么定义的:The Composite Pattern allows you to compose objects into tree structures to represent part-whole 
hierachies.Composite lets clients treat individual objects and composition s of objects uniformly.

     合成模式的各部分结构如下:


    

     关于迭代模式和合成模式在Head First Design Patterns(点击下载) 的第9章Well-Mangaed Collections讲的非常精彩,可以参考学习。






抱歉!评论已关闭.