[JAVA] I wrote a design pattern in kotlin Template 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. This time I will summarize Template.

What is Template?

A design pattern in which a superclass defines a processing framework (similar shared processing) and subclasses define specific content. In the following, we will implement the common process of "displaying characters and character strings 5 times repeatedly" as a concrete process in each subclass.

AbstractDisplay class

Four abstract methods that serve as types are defined, and the specific processing of open, print, and close is implemented in the subclass.

AbstractDisplay.java


abstract class AbstractDisplay {
	public abstract void open();
	public abstract void print();
	public abstract void close();
	public final void display() {
		open();
		for(int i = 0; i < 5; i++) {
			print();
		}
		close();
	}
}

AbstractDisplay.kt


abstract class AbstractDisplay {
    abstract fun open(): Unit
    abstract fun print(): Unit
    abstract fun close(): Unit
    fun display(): Unit {
        open()
        for (i: Int in 1..5) print()
        close()
    }
}

CharDisplay class

It is a subclass that inherits AbstractDisplay which is a template, and in this class, we will implement concrete processing such as formatting and displaying one character passed in the constructor. When inheriting an interface with Kotlin, you didn't need (), but with an abstract class, you need to add () like AbstractDisplay (), which means that the interface doesn't have a constructor, The abstract class is attached by default because the constructor can be implemented.

CharDisplay.java


class CharDisplay extends AbstractDisplay {
	private char ch;
	public CharDisplay(char ch) {
		this.ch = ch;
	}
	@Override
	public void open() {
		System.out.print("<<");
	}
	@Override
	public void print() {
		System.out.print(ch);
	}
	@Override
	public void close() {
		System.out.println(">>");
	}
}

CharDisplay.kt


class CharDisplay(private val ch: Char): AbstractDisplay() {
    override fun open() = print("<<")
    override fun print() = print(ch)
    override fun close() = println(">>")
}

StringDisplay class

It is a subclass that inherits AbstractDisplay which is a template, and in this class, we will implement concrete processing such as formatting and displaying the character string passed in the constructor. If you want to specify an arbitrary number in the for statement in Kotlin and turn it, specify for i..width.

StringDisplay.java


class StringDisplay extends AbstractDisplay {
	private String str;
	private int width;
	public StringDisplay(String str) {
		this.str = str;
		this.width = str.getBytes().length;
	}
	@Override
	public void open() {
		printLine();
	}
	@Override
	public void print() {
		System.out.println("|" + str + "|");
	}
	@Override
	public void close() {
		printLine();
	}
	private void printLine() {
		System.out.print("+");
		for(int i = 0; i < width; i++) {
			System.out.print("-");
		}
		System.out.println("+");
	}
}

StringDisplay.kt


class StringDisplay(private val str: String, private  val width: Int = str.length): AbstractDisplay() {
    override fun open()= printLine()
    override fun print() = println("|" + this.str + "|")
    override fun close() = printLine()
    private fun printLine() {
        print("+")
        for (i: Int in 1..width) print("-")
        println("+")
    }
}

Main class

Since it is a subclass that inherits AbstractDisplay, the display method can be called, and the output is output with the contents defined in each implemented subclass.

TemplateSample.java


public class TemplateSample {
	public static void main(String[] args) {
		AbstractDisplay d1 = new CharDisplay('H');
		AbstractDisplay d2 = new StringDisplay("Hello, World");
		AbstractDisplay d3 = new StringDisplay("Hello World!!");
		
		d1.display();
		d2.display();
		d3.display();
	}
}

Template.kt


fun main(args: Array<String>){
    val d1: AbstractDisplay = CharDisplay('H')
    val d2: AbstractDisplay = StringDisplay("Hello, World")
    val d3: AbstractDisplay = StringDisplay("Hello World!!")

    d1.display()
    d2.display()
    d3.display()
}
<<HHHHH>>
+------------+
|Hello, World|
|Hello, World|
|Hello, World|
|Hello, World|
|Hello, World|
+------------+
+-------------+
|Hello World!!|
|Hello World!!|
|Hello World!!|
|Hello World!!|
|Hello World!!|
+-------------+

Class diagram

image.png

Impressions

reference

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

Introduction to Kotlin for Java Programmers Reverse Kotlin

Recommended Posts

I wrote a design pattern in kotlin Template edition
I wrote a design pattern in kotlin Factory edition
I wrote a design pattern in kotlin Builder 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, Iterator edition
A memo that I wrote a quicksort in Python
Learn the design pattern "Template Method" in Python
I wrote a class in Python3 and Java
I wrote a Japanese parser in Japanese using pyparsing.
Design Pattern #Template Method
I wrote python in Japanese
Template Method pattern in Java
Python Design Pattern --Template method
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 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 "Prototype" in Python
I want to print in a comprehension
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Command" in Python
Learn the design pattern "Visitor" 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 "Iterator" in Python
Learn the design pattern "Strategy" 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
[Fundamental Information Technology Engineer Examination] I wrote a linear search algorithm in Python.
I wrote a PyPI module that extends the parameter style in Python's sqlite3 module
Learn the design pattern "Abstract Factory" in Python
Delete data in a pattern with Redis Cluster
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
[PyTorch] I was a little lost in torch.max ()
Create a loop antenna pattern in Python in KiCad
[Gang of Four] Design pattern learning --Template Method
I made a simple RSS reader ~ C edition ~
I made a Caesar cryptographic program in Python.