1. A simple mockup for ArrayList
package edu.xmu.designPattern.DesignPattern_Iterator; public class ArrayList { private Object[] objects = new Object[10]; private int index = 0; public void add(Object o) { if (index == objects.length) { Object[] newObjects = new Object[objects.length * 2]; System.arraycopy(objects, 0, newObjects, 0, objects.length); objects = newObjects; } objects[index] = obj; index++; } public int size() { return index; } }
package edu.xmu.designPattern.DesignPattern_Iterator; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ArrayListTest { @Test public void test() { ArrayList list = new ArrayList(); for (int i = 0; i < 15; i++) { list.add(new Object()); } assertEquals(15, list.size()); } }
Comments: The benefits of using ArrayList instead of using raw list is that we don't have to worry about the size of the list. It will expand automatically.
2. A simple mockup for LinkedList
package edu.xmu.designPattern.DesignPattern_Iterator; public class Node { private Object data; private Node next; public Node() { super(); } public Node(Object currentObject, Node next) { super(); this.data = currentObject; this.next = next; } public void add(Node node) { if (null == next) { next = node; } else { next.add(node); } } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }
package edu.xmu.designPattern.DesignPattern_Iterator; public class LinkedList { private Node header = null; private int size = 0; public void add(Object obj) { if (null == header) { header = new Node(obj, null); } else { header.add(new Node(obj, null)); } size++; } public int size() { return size; } }
package edu.xmu.designPattern.DesignPattern_Iterator; import static org.junit.Assert.assertEquals; import org.junit.Test; public class LinkedListTest { @Test public void test() { LinkedList list = new LinkedList(); for (int i = 0; i < 15; i++) { list.add(new Cat(i, "Cat" + i)); } assertEquals(15, list.size()); } }
Comments: This is a simple mockup for one-directional LinkedList.
3. Take container's replaceability into consideration.
1) How can we switch the implementation of List from ArrayList to LinkedList without changing code of using them?
Put it another way, how can we reduce the coupling between List and code that using this List?
We can use Interface. And let ArrayList and LinkedList implements this Interface.
package edu.xmu.designPattern.DesignPattern_Iterator; public interface Collection { public void add(Object obj); public int size(); }
package edu.xmu.designPattern.DesignPattern_Iterator; import static org.junit.Assert.assertEquals; import org.junit.Test; public class LinkedListTest { @Test public void test() { // Collection list = new ArrayList(); Collection list = new LinkedList(); for (int i = 0; i < 15; i++) { list.add(new Cat(i, "Cat" + i)); } assertEquals(15, list.size()); } }
Comments: Interface Oriented Programming.
4. Here is another important part of List fuction: Traversal --> This fuction is used quite often.
How can we get every single Object from this List?
1) The way we traverse an ArrayList:
package edu.xmu.designPattern.DesignPattern_Iterator; import org.junit.Test; public class ArrayListTest { @Test public void test() { ArrayList list = new ArrayList(); for (int i = 0; i < 15; i++) { list.add(new Cat(i, "Cat" + i)); } for(int i = 0; i < list.size(); i++) { Cat cat = list.get(i); } } }
2) The way we traverse a LinkedList:
package edu.xmu.designPattern.DesignPattern_Iterator; import static org.junit.Assert.assertEquals; import org.junit.Test; public class LinkedListTest { @Test public void test() { LinkedList list = new LinkedList(); for (int i = 0; i < 15; i++) { list.add(new Cat(i, "Cat" + i)); } Node currentNode = list.getHeader(); while (null != currentNode) { Cat cat = (Cat) currentNode.getData(); currentNode = currentNode.next(); } } }
Comments:
1) Q: Why can't we define this in interface, like get(int index)?
A: It's ok when using get(int index) for ArrayList because it's list inside which is convenient for random access.
But when it comes to LinkedList when traversing using get(int index), it would have to find the element from head to tail.
The time cost for traversal in ArrayList is O(n). The time cost for traversal in LinkedList is O(n^2) = (1 + 2 + 3 + 4 + ... + n);
So we cannot using this to traverse all the list.
E: And it may also possible for us to implements this Interface using the relization of Binary-Tree or some other techniques. Should we expose preorder/inorder/postorder traversal to the client?
2) Q: So, how can we figure out an easy way which have not only reduced the coupling between Implementation and Usage but also reduced the time cost for LinkedList?
A: Think about Iterator Design Pattern as a solution.
3) Now the problem is that different implementation may have different ways of traversal. How can we define a unified way to traversal them?
5. A simple mockup for ArrayList Iterator
1) Iterator interface
package edu.xmu.designPattern.DesignPattern_Iterator; public interface Iterator { public Object next(); public boolean hasNext(); }
2) ArrayList implementation
package edu.xmu.designPattern.DesignPattern_Iterator; public class ArrayList implements Collection { private Object[] objects = new Object[10]; private int index = 0; public void add(Object obj) { if (index == objects.length) { Object[] newObjects = new Object[objects.length * 2]; System.arraycopy(objects, 0, newObjects, 0, objects.length); objects = newObjects; } objects[index] = obj; index++; } public int size() { return index; } public Iterator iterator() { return new ArrayListIterator(); } private class ArrayListIterator implements Iterator { private int currentIndex = 0; public Object next() { Object currentObject = objects[currentIndex]; currentIndex++; return currentObject; } public boolean hasNext() { if (currentIndex > index || null == objects[currentIndex]) { System.out.println("no next"); return false; } else { System.out.println("has next"); return true; } } } }
3) ArrayList test case
package edu.xmu.designPattern.DesignPattern_Iterator; import org.junit.Test; public class ArrayListTest { @Test public void test() { Collection list = new ArrayList(); for (int i = 0; i < 15; i++) { list.add(new Cat(i, "Cat" + i)); } for (Iterator iter = list.iterator(); iter.hasNext();) { Cat cat = (Cat) iter.next(); System.out.println(cat); } } }
4) Output is correct.
6. A simple mockup for LinkedList Iterator
1) The implementation for LinkedList Iterator
package edu.xmu.designPattern.DesignPattern_Iterator; public class LinkedList implements Collection { private Node header = null; private int size = 0; public void add(Object obj) { if (null == header) { header = new Node(obj, null); } else { header.add(new Node(obj, null)); } size++; } public int size() { return size; } public Iterator iterator() { return new LinkedListIterator(); } private class LinkedListIterator implements Iterator { private Node currentNode = header; public Object next() { if (currentNode == header) { Node temp = header; currentNode = header.getNext(); return temp.getData(); } else { Node temp = currentNode.getNext(); currentNode = temp; return temp.getData(); } } public boolean hasNext() { if (null != currentNode.getNext()) { return true; } else { return false; } } } }
2) The test case
package edu.xmu.designPattern.DesignPattern_Iterator; import org.junit.Test; public class LinkedListTest { @Test public void test() { LinkedList list = new LinkedList(); for (int i = 0; i < 15; i++) { list.add(new Cat(i, "Cat" + i)); } for (Iterator iter = list.iterator(); iter.hasNext();) { System.out.println((Cat) iter.next()); } } }
3) The output is correct.
相关推荐
Design Pattern: Iterator 模式 Mediator 模式 Memento 模式 Observer 模式 State 模式 Strategy 模式 Template Method 模式 Visitor 模式 Guarded Suspension 模式 Producer Consumer 模式 ...
23种设计模式(Design Pattern)的C++实现范例,包括下面列出的各种模式,代码包含较详细注释。另外附上“设计模式迷你手册.chm”供参考。 注:项目在 VS2008 下使用。 创建型: 抽象工厂模式(Abstract Factory) 生成...
Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....
Head First Design Pattern 中文版本 1 Welcome to Design Patterns: an introduction 1 2 Keeping your Objects in the know: the Observer Pattern 37 3 Decorating Objects: the Decorator Pattern 79 4 Baking ...
It starts with a general introduction to all types of programming patterns and goes on to describe 10 of the most popular design patterns in detail: Singleton, Iterator, Adapter, Decorator, State, ...
5.4 ITERATOR(迭代器)—对象行为型 模式 171 5.5 MEDIATOR(中介者)—对象行为型 模式 181 5.6 MEMENTO(备忘录)—对象行为型 模式 188 5.7 OBSERVER(观察者)—对象行为型 模式 194 5.8 STATE(状态)—对象...
★第1章至第11章陆续介绍了设计模式:Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton、Command、Adapter、Facade、TemplatMethod、Iterator、Composite、State、Proxy。 ★第12章介绍...
Java design patterns with the Simplest real world examples which are easy to understand & remember as well. Table of Contents PREFACE ...ITERATOR PATTERN INTERPRETER PATTERN MEMENTO PATTERN
If you have ever bought any programming books, you might have noticed that there are two types of them: books that ...Iterator Mediator Memento Null Object Observer State Strategy Template Method Visitor
• What Is a Design Pattern? • Design Patterns in Smalltalk MVC • Describing Design Patterns • The Catalog of Design Patterns • Organizing the Catalog • How Design Patterns Solve Design ...
1. The design pattern “Iterator” can be viewed as a special case of which patter
1. The design pattern “Iterator” can be viewed as a special case of which patter
CoreJava-DesignPattern 创意设计模式 -- Abstract Factory - Done -- Builder - Done -- Factory Method -- Object Pool -- Prototype - Done -- Singleton - Done 结构设计模式 -- Adapter -- Bridge -- ...
Library is an example of policy-based design and employs template meta-programming. We also present the Policy Adapter implementation pattern, a strategy which can also be used to generate new ...
自定义语言的实现——解释器模式(五) 自定义语言的实现——解释器模式(六) 迭代器模式-Iterator Pattern 遍历聚合对象中的元素——迭代器模式(一) 遍历聚合对象中的元素——迭代器模式(二) 遍历聚合对象中的...
第1章到第11章陆续介绍的设计模式为Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton,Command、Adapter、Facade、TemplateMethod、Iterator、Composite、State、Proxy。最后三章比较...
Reusable Approaches for Object-Oriented... Work with the behavioral patterns such as chain of responsibility, command, iterator, mediator and more Apply functional design patterns such as Monad and more
您已经提供了一个迭代器类Iterator ,用户可以创建它来遍历整个表达式树。 该迭代器的特殊之处在于它多次访问树的每个节点。 没有子节点的节点将被访问一次。 有一个孩子的节点被访问两次(访问孩子之前和之后)。 ...