Introduction to Design Patterns (Iterator)

This article summarizes Iterator. According to wikipedia, "By making the means of enumerating the elements of a container object independent, we provide an iterator that does not depend on the internal specifications of the container." Reference: Iterator pattern

A programming language has a mechanism for grouping data such as arrays, lists, and hash tables into a single object, each of which has a suitable usage, and this pattern iterates over the elements of the grouped object.

** Main characters **

no name role
1 Iterator Interface that defines methods for sequential access to objects
2 Iterator concrete class Implement methods to access objects sequentially
3 Aggregate An interface that defines a method that returns a collection iterator
4 Concrete class of aggregates Implement a method that holds a collection and returns an iterator

** Implement the pattern ** I would like to implement multiple restaurant menus according to the design pattern, imagining the food code of a commercial complex. Here, as an example, we define the menus of two stores, "hamburger" and "okonomiyaki". We also assume that each store holds data in different forms (arrays and lists).

** Iterator **

Iterator.java


public interface Iterator {
    boolean hasNext();
    Object next();
}

** Iterator concrete class **

SandwichMenuIterator.java


import java.util.ArrayList;
public class SandwichMenuIterator implements Iterator {
    ArrayList<MenuItem> items = new ArrayList<>();
    int position = 0;


    public SandwichMenuIterator(ArrayList<MenuItem> items) {
        this.items = items;
    }
    public Object next() {
        MenuItem mi = items.get(this.position);
        this.position++;
        return mi;
    }
    public boolean hasNext() {
        if (this.position >= this.items.size()) return false;
        if (this.items.get(this.position) == null) return false;
        return true;
    }
}

OkonomiyakiMenuIterator.java


public class OkonomiyakiMenuIterator implements Iterator {
    MenuItem[] items;
    int position = 0;

    public OkonomiyakiMenuIterator(MenuItem[] items) {
        this.items = items;
    }
    public Object next() {
        MenuItem mi = this.items[this.position];
        this.position++;
        return mi;
    }
    public boolean hasNext() {
        if (this.position >= this.items.length) return false;
        if (this.items[this.position] == null) return false;
        return true;
    }
}

** Aggregate **

Menu.java


public interface Menu {
    public Iterator createIterator();
}

** Concrete class of aggregate **

SandwichMenu.java


import java.util.ArrayList;
public class SandwichMenu implements Menu {
    ArrayList<MenuItem> menuItems = new ArrayList<>();

    public SandwichMenu() {
        addItem("Hamburger", "Ordinary sandwich", true, 120);
        addItem("cheeseburger", "Sandwich with cheese", true, 240);
        addItem("Fish burger", "Fried fish sandwich", true, 320);
    }
    public void addItem(String name, String desc, Boolean coffee, Integer price) {
        MenuItem mi = new MenuItem(name, desc, coffee, price);
        menuItems.add(mi);
    }
    public Iterator createIterator() {
        return new SandwichMenuIterator(menuItems);
    }
    public ArrayList<MenuItem> getMenuItems() {
        return menuItems;
    }
}

OkonomiyakiMenu.java


public class OkonomiyakiMenu implements Menu {
    static final int MAX_ITEMS = 2;
    MenuItem[] menuItems;
    Integer cnt = 0;

    public OkonomiyakiMenu() {
        menuItems = new MenuItem[MAX_ITEMS];
        addItem("Pork ball", "Grilled food using local pork", false, 600);
        addItem("Modern grilled", "Grilled dishes using local vegetables and noodles", false, 750);
    }
    public void addItem(String name, String desc, Boolean coffee, Integer price) {
        MenuItem mi = new MenuItem(name, desc, coffee, price);
        menuItems[cnt] = mi;
        cnt++;
    }
    public Iterator createIterator() {
        return new OkonomiyakiMenuIterator(menuItems);
    }
    public MenuItem[] getMenuItems() {
        return menuItems;
    }
}

** Class that holds menu data **

MenuItem.java


public class MenuItem {
    String name;
    String desc;
    Boolean coffee;
    Integer price;

    public MenuItem(String name, String desc, Boolean coffee, Integer price) {
        this.name = name;
        this.desc = desc;
        this.coffee = coffee;
        this.price = price;
    }

    public String getName() { return name; }
    public String getDesc() { return desc; }
    public Boolean getCoffee() { return coffee; }
    public Integer getPrice() { return price; }
}

** Main class **

Main.java


public class Main {
    public static void main(String args[]) {
        SandwichMenu sm = new SandwichMenu();
        OkonomiyakiMenu om = new OkonomiyakiMenu();
        Iterator sandwichIterator = sm.createIterator();
        Iterator okonomiyakiIterator = om.createIterator();
        printMenu(sandwichIterator);
        printMenu(okonomiyakiIterator);
    }
    public static void printMenu(Iterator iterator) {
        while (iterator.hasNext()) {
            MenuItem mi = (MenuItem)iterator.next();
            System.out.print(mi.getName());
            if(mi.getCoffee()) System.out.print("(With coffee)");
            System.out.println("," + mi.getPrice());
            System.out.println("--" + mi.getDesc());
        }
    }
}

result


$java Main
Hamburger(With coffee),120
--Ordinary sandwich
cheeseburger(With coffee),240
--Sandwich with cheese
Fish burger(With coffee),320
--Fried fish sandwich
Pork ball,600
--Grilled food using local pork
Modern grilled,750
--Grilled dishes using local vegetables and noodles

The Iterator pattern is to implement a function that sequentially accesses an object that collects data. This time, for two objects of different data types, we created a class (○○ MenuIterator.java) that accesses each object in sequence and output it on the screen. The Java language "java.util.Collection" interface implements the Iterator method, so it's easy to imagine.

Reference: [Head First Design Patterns-Design Patterns to Remember with Your Head and Body] (https://www.amazon.co.jp/Head-First%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3-%E2%80%95%E9%A0%AD%E3%81%A8%E3%81%8B%E3%82%89%E3%81%A0%E3%81%A7%E8%A6%9A%E3%81%88%E3%82%8B%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%E3%81%AE%E5%9F%BA%E6%9C%AC-Eric-Freeman/dp/4873112494)

Recommended Posts

Introduction to Design Patterns (Iterator)
Introduction to design patterns (introduction)
Introduction to Design Patterns (Builder)
Introduction to Design Patterns (Composite)
Introduction to design patterns (Flyweight)
Introduction to Design Patterns (Strategy)
Introduction to Design Patterns (Abstract Factory)
Important design patterns to improve maintainability
Introduction to Ruby 2
Introduction to SWING
Design pattern ~ Iterator ~
Java Design Patterns
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
[Java] Introduction to Java
Introduction to migration
Introduction to java
Introduction to Doma
Introduction to JAR files
Introduction to Ratpack (8)-Session
Introduction to RSpec 1. Test, RSpec
Introduction to bit operation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
Introduction to PlayFramework 2.7 ① Overview
Introduction to Android Layout
Introduction to Practical Programming
Introduction to javadoc command
Introduction to jar command
Introduction to Ratpack (2)-Architecture
Introduction to lambda expression
Introduction to java command
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Study GoF design patterns
Introduction to javac command
I read Hiroshi Yuki "Introduction to Design Patterns Learned in Java Language" (SB Creative)
Read design patterns in Ruby
Introduction to RSpec 5. Controller specs
Introduction to Android application development
Introduction to RSpec 3. Model specs
Introduction to Ratpack (5) --Json & Registry
Introduction to Metabase ~ Environment Construction ~
(Dot installation) Introduction to Java8_Impression
Introduction to Micronaut 2 ~ Unit test ~
Introduction to JUnit (study memo)
Introduction to Spring Boot ① ~ DI ~
[Java] Introduction to lambda expressions
Introduction to Spring Boot ② ~ AOP ~
Introduction to Apache Beam (2) ~ ParDo ~
[Ruby] Introduction to Ruby Error statement
Introduction to EHRbase 2-REST API
[Java] Introduction to Stream API
Introduction to Spring Boot Part 1
Introduction to Ratpack (1) --What is Ratpack?
XVim2 introduction memo to Xcode12.3
Why design patterns are needed
[Java] Summary of design patterns
Introduction to RSpec-Everyday Rails Summary-
[Introduction to rock-paper-scissors games] Java
Design patterns to try with Swift-Iterator patterns that support Arrays and Dictionary