Understand the Iterator pattern by comparing Java and JavaScript code

Introduction

Details and other patterns will be written in ** Understanding design patterns by comparing implementations in JavaScript and Java **. I wrote an example of JavaScript by looking at Java. We do not take advantage of differences in features such as class type / prototype type, typed strength, and access modifiers. (Some getters are not needed) Please note.

Iterator pattern

When a lot of things are gathered, it is for pointing to them in order and performing the process of scanning the whole The English word iterate means ** repeat ** something. Sometimes called ** iterator ** in Japanese

Implementation example in Java

There are several books on the bookshelf, and a program that counts the number of books on each bookshelf

Class diagram

Iterator.png

code

Main.java


public class Main {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("Around the World in 80 Days"));
        bookShelf.appendBook(new Book("Bible"));
        bookShelf.appendBook(new Book("Chinderella"));
        bookShelf.appendBook(new Book("Dabby-Long-Legs"));
        Iterator it = bookShelf.iterator();
        while (it.hasNext()) {
            Book book = (Book)it.next();
            System.out.println(book.getName());
        }        
    }
}

Aggregate.java


public interface Aggregate {
    public abstract Iterator iterator();
}

BookShelf.java


public class BookShelf implements Aggregate {
    private Book[] books;
    private int last = 0;

    public BookShelf(int maxsize) {
        this.books = new Book[maxsize];
    }
    public Book getBookAt(int index) {
        return books[index];
    }
    public void appendBook(Book book) {
        this.books[last] = book;
        last++;
    }
    public int getLength() {
        return last;
    }
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}

Book.java


public class Book {
    private String name;

    public Book(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

Iterator.java


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

BookShelfIterator.java


public class BookShelfIterator implements Iterator {
    private BookShelf bookShelf;
    private int index;

    public BookShelfIterator(BookShelf bookShelf) {
        this.bookShelf = bookShelf;
        this.index = 0;
    }
    public boolean hasNext() {
        if (index < bookShelf.getLength()) {
            return true;
        } else {
            return false;
        }
    }
    public Object next() {
        Book book = bookShelf.getBookAt(index);
        index++;
        return book;
    }
}

JavaScript example

code

index.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Iterator</title>
</head>
<body>
    <script src="Main.js"></script>
    <script src="Interface.js"></script>
    <script src="Aggregate.js"></script>
    <script src="BookShelf.js"></script>
    <script src="Book.js"></script>
    <script src="iterator.js"></script>
    <script src="BookShelfIterator.js"></script>
</body>
</html>

Main.js


MAIN = {};
MAIN.init = function() {
    var bookShelf = new BookShelf();
    bookShelf.appendBook(new Book("Around the World in 80 Days"));
    bookShelf.appendBook(new Book("Bible"));
    bookShelf.appendBook(new Book("Chinderella"));
    bookShelf.appendBook(new Book("Dabby-Long=legs"));
    var it = bookShelf.iterator();
    while (it.hasNext()) {
        var book = it.next();
        console.log(book.name);
    }
};

window.addEventListener("load", MAIN.init);

Interface.js


/**
 * @namespace INTERFACE
 */
INTERFACE = {};

/**
 *Determine if they have the same properties
 * @static
 * @method implements
 */
INTERFACE.implements = function(child, Pr) {
    var parent = new Pr();
    for (var p in parent) {
        if (!(p in child)) {
            console.error(child.constructor.name + "class(function)To" + p + "The method has not been declared.");
        }
    }
};

Aggregate.js


var Aggregate = function() {};
Aggregate.prototype.iterator = function() {};

BookShelf.js


var BookShelf = function() {
    this.books = [];
    this.last = 0;

    INTERFACE.implements(this, Aggregate);
};

BookShelf.prototype = {
    constructor: BookShelf,

    getBookAt: function(index) {
        return this.books[index];
    },
    appendBook: function(book) {
        this.books[this.last] = book;
        this.last += 1;
    },
    getLength: function() {
        return this.last;
    },
    iterator: function() {
        return new BookShelfIterator(this);
    }
};

Book.js


var Book = function(name) {
    this.name = name;
};

Book.prototype.getName = function() {
    return this.name;
};

Iterator.js


var Iterator = function() {};
Iterator.prototype = {
    constructor: Iterator,

    hasNext: function() {},
    next: function() {}
};

BookShelfIterator.js


var BookShelfIterator = function(bookShelf) {
    this.bookShelf = bookShelf;
    this.index = 0;

    INTERFACE.implements(this, Iterator);
};

BookShelfIterator.prototype = {
    constructor: BookShelfIterator,

    hasNext: function() {
        if (this.index < this.bookShelf.getLength()) {
            return true;
        } else {
            return false;
        }
    },
    next: function() {
        var book = this.bookShelf.getBookAt(this.index);
        this.index += 1;
        return book;
    }
}

Iterator pattern in JavaScript written in a book

The Iterator pattern is behavior, so it would be nice to have hasNext () and next (), right? I feel like I can't reuse it, so a little. .. .. I feel like For your reference

index.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Iterator</title>
</head>
<body>
    <script src="Main.js"></script>
</body>
</html>

Main.js


MAIN = {};

MAIN.init = function() {
    while(egg.hasNext()) {
        console.log(egg.next());
    }
};

var egg = (function() {
    var index = 0,
        data = [1, 2, 3, 4, 5],
        length = data.length;

    return {
        next: function() {
            var element;
            if (!this.hasNext()) {
                return null;
            }
            element = data[index];
            index = index + 1;
            return element;
        },

        hasNext: function() {
            return index < length;
        }
    };
}());

window.addEventListener("load", MAIN.init);

Characters in the Iterator pattern

** The role of Iterator **

A role that determines the interface that scans elements in order Sample program ⇒ Iterator (interface)

** The role of Concreate Iterator **

A role that actually implements the interface defined by the Iterator role Sample program ⇒ BookShelfIterator (class)

** The role of Aggregate **

The role that defines the interface that creates the Iterator role Sample program ⇒ Aggregate (interface)

** The role of Concreate Aggregate **

The role that actually implements the interface defined by the Aggregate role Sample program ⇒ BookShelf (class)

Iterator pattern class diagram

クラス図2.png

Need for Iterator pattern

Even if you don't use the Iterator pattern, you can use a for statement, etc. The main reason for using Iterator is that iterator allows you to count separately from the implementation.

Iterator type

In this example, it's a simple one that scans forward only once, but there are others.

Related patterns

reference

[Introduction to Design Patterns Learned in the Enhanced and Revised Java Language](https://www.amazon.co.jp/%E5%A2%97%E8%A3%9C%E6%94%B9%E8%A8%82% E7% 89% 88Java% E8% A8% 80% E8% AA% 9E% E3% 81% A7% E5% AD% A6% E3% 81% B6% E3% 83% 87% E3% 82% B6% E3% 82% A4% E3% 83% B3% E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3% E5% 85% A5% E9% 96% 80-% E7% B5 % 90% E5% 9F% 8E-% E6% B5% A9 / dp / 4797327030) JavaScript pattern-how to do good applications

Recommended Posts

Understand the Iterator pattern by comparing Java and JavaScript code
Understand the Singleton pattern by comparing Java and JavaScript code
Java and JavaScript
[Java] Understand the difference between List and Set
Understand bugs by implementing and analyzing them (1) Deadlock (Java)
Java classes and instances to understand in the figure
Introduction to Effective java by practicing and learning (Builder pattern)
I didn't understand the behavior of Java Scanner and .nextLine ().
[For beginners] About the JavaScript syntax explained by Java Gold
[Rails] Understand migration up and down by comparing with change
[Java] Appropriate introduction by the people of Tempa Java Part 0 (Code rules)
Guess the character code in Java
[java8] To understand the Stream API
Java 15 implementation and VS Code preferences
Understand the difference between each_with_index and each.with_index
Java 9 new features and sample code
Arbitrary string creation code by Java
Java pass by value and pass by reference
The road from JavaScript to Java
Web application structure by Java and processing flow in the presentation layer
A collection of phrases that impresses the "different feeling" of Java and JavaScript
Beginners can see the Devise code and understand the mechanism softly [registrations new]
Understand the difference between int and Integer and BigInteger in java and float and double
Java reference to understand in the figure
Link Java and C ++ code with SWIG
Let's try WebSocket with Java and javascript!
I tried to implement the Iterator pattern
[Java 7] Divide the Java list and execute the process
Execute Java code stored on the clipboard.
The story received by Java SE11 silver
I studied the State pattern and the Strategy pattern
[Java8] Search the directory and get the file
Page number logic and reference code (java)
Java vs. JavaScript: What ’s the Difference?
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
Build Apache and Tomcat environment with Docker. By the way, Maven & Java cooperation
Parse the date and time string formatted by the C asctime function in Java