[JAVA] I wrote a design pattern in kotlin, Iterator edition

To learn the concept of Interface and the reusability of objects, which are important in object orientation ["Introduction to design patterns learned in 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 / ref = sr_1_1? __mk_ja_JP =% E3% 82% AB % E3% 82% BF% E3% 82% AB% E3% 83% 8A & keywords = java% 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 I learned about% 85% A5% E9% 96% 80 & qid = 1559563427 & s = gateway & sr = 8-1) and decided to write in Java and then in kotlin. First, I will summarize Iterator.

What is Iterator

It is a pattern that scans the elements of a set such as List in order from the beginning, which means "iterator" in Japanese.

Aggregate interface

The Agreagate interface has the role of an aggregate that can be counted. Interfaces are not inherited, they have a role to force them to implement methods.

Aggregate.java


interface Aggregate {
	public abstract Iterator iterator(); 
}

Aggregate.kt


interface Aggregate {
    fun iterator(): Iterator
}

Iterator interface

An interface that has methods for manipulating elements because it plays a role in counting elements. Here, the movement of the next method is important, and it is necessary to acquire the element and advance the index so that the next element can be acquired. Also, after receiving a review of this Iterator interface, it was said that the Object type in Java is equivalent to Any? In Kotlin. The difference between Any and Any? Is whether or not it allows nulls, and the API has been modified to allow nulls for various implementations.

Iterator.java


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

Iterator.kt


interface Iterator {
    fun hasNext(): Boolean
    fun next(): Any?
}

Member class

Create a class that will be retrieved as an element. With kotlin, you can get it with member.name without implementing getter / setter.

Member.java


class Member {
	private String name;
	public Member(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

Member.kt


class Member(val name: String)

Staff class

Create a Staff class as an implementation of Aggregate, and make the Staff class a collection of Members. Implement the Iterator method defined in the interface.

Staff.java


class Staff implements Aggregate{
	private Member[] members;
	private int last;
	
	public Staff(int maxsize) {
		this.members = new Member[maxsize];
	}

	public Member getMemberAt(int index) {
		return members[index];
	}
	public void appendMember(Member member) {
		this.members[last] = member;
		last++;
	}
	public int getLength() {
		return last;
	}
	public Iterator iterator() {
		return new StaffIterator(this);
	}
}

Staff.kt


class Staff internal constructor(private val maxSize: Int): Aggregate {
    private val members: Array<Member?> = arrayOfNulls(maxSize)
    private var last: Int = 0

    fun getMemberAt(index: Int): Member? = members[index]

    fun appendMember(member: Member) {
        members[this.last] = member
        this.last++
    }

    fun getLength():Int = this.last

    override fun iterator(): Iterator = StaffIterator(this)
}

StaffIterator class

Create the StaffIterator class as an implementation of Iteraltor and implement the methods so that Staff can be scanned. In the next method, the element is acquired and the index is advanced to the next, and it has the role of i ++ in the For syntax. Also, I allowed Null using the next method C Any? Of the Iterator interface, but I did not intend to return the member object as null, so I set Any, which is Non-Null, as the return value.

StaffIterator.java


class StaffIterator implements Iterator{
	private Staff staff;
	private int index;
	public StaffIterator(Staff staff) {
		this.staff = staff;
		this.index = 0;
	}
	public boolean hasNext() {
		if(index < staff.getLength()) {
			return true;
		}else {
			return false;			
		}
	}
	public Object next() {
		Member member = staff.getMemberAt(index);
		index++;
		return member;
	}
}

StaffIterator.kt


class StaffIterator(private val staff: Staff): Iterator {
    private var index: Int = 0
    override fun hasNext(): Boolean = index < staff.getLength()

    override fun next(): Any {
        val member: Member = staff.getMemberAt(index) as Member
        index++
        return member
    }
}

Main class

This is the Main class that actually operates the above class. The point here is that the implementation of Staff does not interfere with the while statement.

IteratorSample.java


public class IteratorSample {
	public static void main(String[] args) {
		Staff staff = new Staff(3);
		staff.appendMember(new Member("sato"));
		staff.appendMember(new Member("suzuki"));
		staff.appendMember(new Member("saito"));
		Iterator it = staff.iterator();
		while(it.hasNext()) {
			Member member = (Member)it.next();
			System.out.println(member.getName());
		}
	}
}

IteratorSample.kt


fun main(args: Array<String>){
    val staff = Staff(3).apply {
        appendMember(Member("sato"))
        appendMember(Member("suzuki"))
        appendMember(Member("saito"))
    }
    val it: Iterator = staff.iterator()
    while (it.hasNext()) {
        val member: Member = it.next() as Member
        println(member.name)
    }
}

Execution result


sato
suzuki
saito

Class diagram

image.png

Impressions

Problem 1-1

Changed the array of Staff class to Vector. As a result of actually implementing it, I was able to confirm that the range of influence of the change was within the Staff class, and learned the importance of low dependency.

package practice.design_pattern_java;

import java.util.Vector;

interface Aggregate {
	public abstract Iterator iterator(); 
}

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

class Member {
	private String name;
	public Member(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

class StaffIterator implements Iterator{
	private Staff staff;
	private int index;
	public StaffIterator(Staff staff) {
		this.staff = staff;
		this.index = 0;
	}
	public boolean hasNext() {
		if(index < staff.getLength()) {
			return true;
		}else {
			return false;			
		}
	}
	public Object next() {
		Member member = staff.getMemberAt(index);
		index++;
		return member;
	}
}

class Staff implements Aggregate{
	private Vector<Member> members = new Vector<Member>();
	private int last;

	public Member getMemberAt(int index) {
		return members.get(index);
	}
	public void appendMember(Member member) {
		this.members.addElement(member);;
		last++;
	}
	public int getLength() {
		return last;
	}
	public Iterator iterator() {
		return new StaffIterator(this);
	}
}

public class IteratorVectorSample {
	public static void main(String[] args) {
		Staff staff = new Staff();
		staff.appendMember(new Member("sato"));
		staff.appendMember(new Member("suzuki"));
		staff.appendMember(new Member("saito"));
		Iterator it = staff.iterator();
		while(it.hasNext()) {
			Member member = (Member)it.next();
			System.out.println(member.getName());
		}
	}
}

reference

It was very easy to read and understand by referring to the following.

Introduction to Kotlin for Java Programmers

For Kotlin's Any, I referred to the following. Where Java programmers tend to trip over Kotlin

Recommended Posts

I wrote a design pattern in kotlin, Iterator edition
I wrote a design pattern in kotlin Singleton edition
I wrote a design pattern in kotlin Adapter edition
I wrote a design pattern in kotlin Template edition
I wrote a design pattern in kotlin Prototype
Learn the design pattern "Iterator" in Python
A memo that I wrote a quicksort in Python
I wrote a class in Python3 and Java
I wrote a Japanese parser in Japanese using pyparsing.
Iterator pattern in Java
I wrote python in Japanese
I wrote a script to get a popular site in Japan
I wrote a script that splits the image in two
I get a UnicodeDecodeError in mecab-python3
I get a KeyError in pyclustering.xmeans
I wrote a function to load a Git extension script in Python
I wrote Fizz Buzz in Python
I wrote Gray Scale in Pytorch
I wrote a script to extract a web page link in Python
I wrote the queue in Python
I participated in AtCoder (ABC169 edition)
I wrote the stack in Python
I wrote a code to convert quaternions to z-y-x Euler angles in Python
[Python] I forcibly wrote a short Perlin noise generation function in Numpy.
I wrote FizzBuzz in python using a support vector machine (library LIVSVM).
Learn the design pattern "Builder" in Python
I want to print in a comprehension
Learn the design pattern "Flyweight" in Python
I made a payroll program in Python!
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
I wrote the selection sort in C
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "State" in Python
I wrote Project Euler 1 in one liner.
Learn the design pattern "Adapter" in Python
I started Node.js in a virtual environment
I created a password tool in Python.
I wrote the sliding wing in creation.
I wrote a graph like R glmnet in Python for sparse modeling in Lasso
I wrote a PyPI module that extends the parameter style in Python's sqlite3 module
When I get a chromedriver error in Selenium
Learn the design pattern "Abstract Factory" in Python
Learn the design pattern "Template Method" in Python
I want to create a window in Python
I tried playing a typing game in Python
Learn the design pattern "Factory Method" in Python
I wrote "Introduction to Effect Verification" in Python
[Memo] I tried a pivot table in Python
I wrote a script to upload a WordPress plugin
I wrote the hexagonal architecture in go language
I tried adding a Python3 module in C
[PyTorch] I was a little lost in torch.max ()
Create a loop antenna pattern in Python in KiCad
I made a simple RSS reader ~ C edition ~