Iterator Pattern
Iterator Pattern에 대해 설명하는 페이지입니다.
Iterator Pattern
Tags
Design Pattern, Java
1. Introduction
- a.k.a
- Cursor
- Purpose
- Allows for access to the elements of an aggregate object without allowing access to its underlying representation.
- Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Info.
An aggregate object is an object that contains other objects for the purpose of grouping those objects as a unit. It's also called a container or a collection. Examples are linked list and hash table.
- Use When
- Access to elements is needed without access to the entire representation.
- Multiple or concurrent traversals of the elements are needed.
- A uniform interface for traversal is needed.
- Subtle differences exist between the implementation details of various iterators.
2. How to Use (Example)
java
1public class MenuItem {
2 String name;
3 String description;
4 boolean vegetarian;
5 double price;
6
7 public MenuItem(String name, String description, boolean vegetarian, double price) {
8 this.name = name;
9 this.description = description;
10 this.vegetarian = vegatarian;
11 this.price = price;
12 }
13}java
1public interface Menu {
2 public Iterator createIterator();
3}java
1public class DinerMenu implements Menu {
2 MenuItem[] menuItems;
3
4 @Override
5 public Iterator createIterator() {
6 return new DinerMenuIterator(menuItems);
7 }
8}java
1import java.util.Iterator;
2
3public class DinerMenuIterator implements Iterator {
4 MenuItem[] items;
5 int position;
6
7 public DinerMenuIterator(MenuItem[] items) {
8 this.items = items;
9 position = 0;
10 }
11
12 @Override
13 public Object next() {
14 MenuItem menuItem = items[position];
15 position++;
16 return menuItem;
17 }
18
19 @Override
20 public boolea hasNext() {
21 if (position >= items.length)
22 return false;
23 else
24 return true;
25 }
26
27 @Override
28 public void remove() {
29 // code for removing an item and shifting the rest
30 }
31}