//具体工厂public class IteratorFactory<T> implements IIteratorFactory<T>{ @Override public IteratorMap<T> iteratorMap(Map<T,Object> m) { return new IteratorMap<T>(m); } @Override public IteratorCollection<T> iteratorCollection(Collection<T> c) { return new IteratorCollection<T>(c); }}
至此,这个小框架就完成了,我们可以使用它来遍历Collection(List,Set,Queue都是集成自它)和Map:
//测试使用public class TestUse { public static void main(String args[]){ IIteratorFactory<Integer> factory = new IteratorFactory<>(); Collection<Integer> collection = new ArrayList<Integer>(); Map<Integer, Object> map = new LinkedHashMap<>(); for(int i=0;i<10;i){ collection.add(i); map.put(i, i); } IIterator<Integer> iteratorCollection = factory.iteratorCollection(collection); IIterator<Integer> iteratorMap = factory.iteratorMap(map); while(iteratorCollection.hasNext()) System.out.print(iteratorCollection.next()); System.out.println(); while(iteratorMap.hasNext()) System.out.print(iteratorMap.next()); }}
输出:
01234567890123456789
实际情况下,我们可能不应该这么做,以为Collection面向一种对象的容器,Map是面向两种对象的关联容器,但是此例使用抽象工厂模式确实实现了不同容器的 统一遍历方式。
如果一个容器持有的大量对象,他们都直接或间接集成自某一个类,使用访问者模式遍历也是一种很好的方式,具体在后面的访问者模式中会详细介绍。
工厂模式主要就涉及上面介绍的三种:
简单工厂模式是由一个具体的类去创建其他类的实例,父类是相同的,父类是具体的。 工厂方法模式是有一个抽象的父类定义公共接口,子类负责生成具体的对象,这样做的目的是将类的实例化操作延迟到子类中完成。 抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无须指定他们具体的类。它针对的是有多个产品的等级结构。而工厂方法模式针对的是一个产品的等级结构。4、模式(Builder Pattern)
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-33893-8.html
我们加紧建设我们的
不是每个人