I tried to implement the Iterator pattern

Domo is Fugito.

This time, Hiroshi Yuki "Introduction to Design Patterns Learned in Java Language" Design pattern while referring to (SB Creative) We will implement the "Iterator pattern" which is one of the I will.

What is the Iterator pattern?

The Iterator pattern is a collection of things Sometimes, instruct it in order and scan the whole It is for performing the processing to be done. (P.2)

For example, "The identity of the things in the bag one by one. I think it's a program called "search".

In this book, as a sample program, "Enter in the bookshelf" Look up the books and display the names of the books in order. " Is introduced. This time I added an arrangement there "** Display songs in the song list one by one **" I thought I would write the program in the Iterator pattern I will.

Aggregate interface

Aggregate interface counts Represents an "aggregate" of things to do. (P.3)

Here, "Song Aggregate", which stands for "collection of songs" Create an interface called.

public interface SongAggregate {
	public abstract SongIterator songIterator();
}

This interface counts aggregates Declare only the method "songIterator" for.

Iterator interface

The Iterator interface counts elements Acts like a loop variable It is a thing.

Here, create "Song Iterator".

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

Does the hasNext method have the following elements in the "aggregate"? It is for checking. Also, the next method If you have the following element, you will get that element.

Song class

This is a class for expressing each "song".

public class Song {
	private String songName;

	public Song(String s) {
		this.songName = s;
	}

	public String getSongName() {
		return songName;
	}
}

SongList class

This class expresses "a collection of songs". Implement the SongAggregate interface and use abstract methods Override the songIterator method that was there.

public class SongList implements SongAggregate {
	private Song[] songs;
	private int last = 0;

	public SongList(int max) {
		this.songs = new Song[max];
	}

	public Song getSongAt(int id) {
		return songs[id];
	}

	public void appendSong(Song s) {
		this.songs[last] = s;
		last++;
	}

	public int getLength() {
		return last;
	}

	@Override
	public SongIterator songIterator() {
		return new SongListIterator(this);
	}

}

Here the constructor maximizes the song Define SongList instance that can store up to doing. The getSongAt method returns the idth song. The appendSong method is at the end of the array songs [] Stores a new song s. getLength returns the number of songs in the SongList The method. And in the overridden songIterator method, Of the class called SongListIterator that we will create Create an instance and return it as a SongIterator type.

SongListIterator class

Actually scan the SongList class It is a class. Real SongIterator interface Pretending to be over the hasNext method and next method Ride

public class SongListIterator implements SongIterator {
	private SongList songList;
	private int id;

	public SongListIterator(SongList sl) {
		this.songList = sl;
		this.id = 0;
	}

	@Override
	public boolean hasNext() {
		if(id < songList.getLength()) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Object next() {
		Song song = songList.getSongAt(id);
		id++;
		return song;
	}

}

Now you are ready to scan the list. from here Create a Main class to create an actual list and scan I will try.

public class Main {
	public static void main(String[] args) {
 //新しくSongListを作成
		SongList songList = new SongList(5);

 //リストに曲を追加
		songList.appendSong(new Song("So What"));
		songList.appendSong(new Song("Freddie Freeloader"));
		songList.appendSong(new Song("Blue In Green"));
		songList.appendSong(new Song("All Blues"));
		songList.appendSong(new Song("Flamenco Sketches"));

 //SongIteratorのインスタンスを生成
		SongIterator song_it = songList.songIterator();

 //曲をひとつずつ調べる
		while(song_it.hasNext()) {
			Song song = (Song)song_it.next();
			System.out.println(song.getSongName());
		}
	}

}

The execution result is as follows.

So What
Freddie Freeloader
Blue In Green
All Blues
Flamenco Sketches

It seems that it was executed properly. Good grief.

Summary

After all, the point of the Iterator pattern is "** Even if I rewrite the SongList, the songIterator method still works. If it exists and returns the correct SongIterator, the Main message Sod's while loop works without any changes ** " It is at the point. In short, a design that can withstand the expansion of functions It means that it has become. It ’s just “wisdom in the field” I feel like that.

From now on, 23 GoF design patterns will be used like this. I wish I could put it together.

so, that's it for today. It was Puyi.

P.S. "Seniors", opinions on this article, Please feel free to comment if you have any supplements m (_ _) m

Recommended Posts

I tried to implement the Iterator pattern
I tried to implement the Euclidean algorithm in Java
I tried to explain the method
I tried to implement the like function by asynchronous communication
[Swift] I tried to implement the function of the vending machine
I tried to summarize the methods used
I tried to summarize the Stream API
I tried to implement ModanShogi with Kinx
I tried to implement the image preview function with Rails / jQuery
I tried to implement polymorphic related in Nogizaka.
I tried to organize the session in Rails
I tried to implement deep learning in Java
I tried to set tomcat to run the Servlet.
I tried to implement a server using Netty
I tried to implement file upload with Spring MVC
I tried to organize the cases used in programming
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
I tried to summarize the state transition of docker
I tried to decorate the simple calendar a little
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried the Docker tutorial!
I tried the VueJS tutorial!
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
I tried the FizzBuzz problem
I tried to verify yum-cron
[Swift] I tried to implement exception handling for vending machines
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried to increase the processing speed with spiritual engineering
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
I tried to summarize the basic grammar of Ruby briefly
I tried to build the environment little by little using docker
[Rails] I tried to implement batch processing with Rake task
I tried to build the environment of WSL2 + Docker + VSCode
I tried to implement a buggy web application in Kotlin
[Rails] I tried to implement "Like function" using rails and js
I tried validation to unify the way hashtags are written
I tried upgrading from CentOS 6.5 to CentOS 7 with the upgrade tool
I tried to chew C # (indexer)
I tried to summarize iOS 14 support
I tried the Java framework "Quarkus"
[Rails] I tried deleting the application
The story I wanted to unzip
I tried to summarize Java learning (1)
I tried to understand nil guard
I tried to summarize Java 8 now
I tried to chew C # (polymorphism: polymorphism)
I tried to explain Active Hash
I tried to solve the problem of "multi-stage selection" with Ruby
I tried to summarize the words that I often see in docker-compose.yml
Iterator pattern
[Metal] I tried to figure out the flow until rendering using Metal
I tried to implement Ajax processing of like function in Rails
I tried to summarize what was asked at the site-java edition-
I tried to illuminate the Christmas tree in a life game
I tried to sort the data in descending order, ascending order / Rails
I tried to build the environment of PlantUML Server with Docker
Iterator Pattern