[GO] I wrote a design pattern in kotlin Builder 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 write about Builder.

What is Builder?

When constructing a structure, it is a pattern of assembling an instance with a structure, just as it is assembled in each step. The sample program deals with a structure called sentences and Assuming that the text has the following stages and structures, we will define the methods that make up each stage.

  1. Include one title
  1. Contains some strings
  2. Includes some bulleted items

Builder class

A class that defines methods for composing sentences.

Builder.java


abstract class Builder {
	public abstract void makeTitle(String title);
	public abstract void makeString(String str);
	public abstract void makeItems(String[] items);
	public abstract void close();
}

Builder.kt


abstract class Builder {
    abstract fun makeTitle(title: String)
    abstract fun makeString(str: String)
    abstract fun makeItems(items: Array<String>)
    abstract fun close()
}

Director class

This class implements the construct method that constructs the text. The Builder class is passed in the constructor, but since Builder is an abstract class, the inherited subclass is actually included. Since there is no specific subclass declaration, there are no dependencies, Also, the fact that subclasses can be replaced is called exchangeability.

Director.java


class Director {
	private Builder builder;
	public Director(Builder builder) {
		this.builder = builder;
	}
	public void construct() {
		builder.makeTitle("Greeting");
		builder.makeString("From morning to noon");
		builder.makeItems(new String[] {
				"Good morning.",
				"Hello."
		});
		builder.makeString("At night");
		builder.makeItems(new String[] {
				"Good evening.",
				"good night.",
				"goodbye."
		});
		builder.close();
	}
}

Director.kt


class Director(builder: Builder) {
    private var b = builder
    fun construct(){
        b.makeTitle("Greeting")
        b.makeString("From morning to noon")
        b.makeItems(arrayOf("Good morning.", "Hello."))
        b.makeString("At night")
        b.makeItems(arrayOf("Good evening.", "good night.", "goodbye."))
        b.close()
    }
}

TextBuilder class

A class that creates a document using plain text.

When I wrote the for statement in kotlin, I first wrote for (i: Int in 0..items.size -1), but Like for (i: Int in 0 until items.size), until does not count the last number, so it is suitable for Array operation.

Reference: Android development with Kotlin! Let's hold down the basic syntax

With kotlin, you can write a convenient way called String Template (string interpolation). You can embed a string like println ("$ a + $ b = $ {a + b} ") // 2 + 3 = 5.

Reference: What Java programmers find useful with Kotlin

TextBuilder.java


class TextBuilder extends Builder{
	private StringBuffer buffer = new StringBuffer();
	public void makeTitle(String title) {
		buffer.append("================================================\n");
		buffer.append(String.format("[%s]\n", title));
		buffer.append("\n");
	}
	public void makeString(String str) {
		buffer.append(String.format("■%s\n", str));
		buffer.append("\n");
	}
	public void makeItems(String[] items) {
		for (int i = 0; i < items.length; i++) {
			buffer.append(String.format("・%s\n", items[i]));
		}
		buffer.append("\n");
	}
	public void close() {
		buffer.append("================================================\n");
	}
	public String getResult() {
		return buffer.toString();
	}
}

TextBuilder.kt


class TextBuilder: Builder() {
    private var buffer = StringBuffer()
    override fun makeTitle(title: String) {
        buffer.append("================================================\n")
        buffer.append("[$title]\n")
        buffer.append("\n")
    }
    override fun makeString(str: String) {
        buffer.append("■$str\n")
        buffer.append("\n")
    }
    override fun makeItems(items: Array<String>) {
        for (i: Int in 0 until items.size) buffer.append("・${items[i]}\n")
        buffer.append("\n")
    }
    override fun close() {
        buffer.append("================================================\n")
    }
    fun getResult() = buffer.toString()
}

HTMLBuilder class

A class that creates a document using an HTML file.

I was having trouble initializing the writer member with the File class, but I heard that you can use lateinit to delay the value that changes as the process progresses. Also, lateinit is recommended as private because it is difficult to access it from the outside before it is initialized.

Reference: [Delay initialization with Kotlin](https://re-engines.com/2018/11/15/Delay initialization with kotlin /)

You can get the printWriter by using java.io.File # printWriter (), it will be created if the file does not exist and overwritten if it exists. If you want to add it, use ʻappendText ()`.

Reference: I / O (files, networks, etc.)

If you want to change the behavior depending on the existence of the file, use java.io.File # createNewFile (): Boolean.

Reference: Kotlin – Create File – Examples

HTMLBuilder.java


import java.io.*;

class HTMLBuilder extends Builder{
	private String filename;
	private PrintWriter writer;
	public void makeTitle(String title) {
		filename = title + ".html";
		try {
			writer = new PrintWriter(filename);
		} catch (IOException e) {
			e.printStackTrace();
		}
		writer.println(String.format("<html><head><title>%s</title></head><body>", title));
		writer.println(String.format("<h1>%s</h1>", title));
	}
	public void makeString(String str) {
		writer.println(String.format("<p>%s</p>", str));
	}
	public void makeItems(String[] items) {
		writer.println("<ul>");
		for (int i = 0; i < items.length; i++) {
			writer.println(String.format("<li>%s</li>", items[i]));
		}
		writer.println("</ul>");
	}
	public void close() {
		writer.println("</body></html>");
		writer.close();
	}
	public String getResult() {
		return filename;
	}
}

HTMLBuilder.kt


import java.io.File

class HTMLBuilder: Builder() {
    private var filename = String()
    private lateinit var writer:File
    override fun makeTitle(title: String) {
        filename = "$title.html"
        writer = File(filename)
        writer.printWriter().use { it.println("<html><head><title>$filename</title></head><body>") }
        writer.appendText("<h1>$title</h1>\n")
    }
    override fun makeString(str: String) {
        writer.appendText("<p>$str</p>\n")
    }
    override fun makeItems(items: Array<String>) {
        writer.appendText("<ul>\n")
        for (i: Int in 0 until items.size) writer.appendText("<li>${items[i]}</li>\n")
        writer.appendText("</ul>\n")
    }
    override fun close() {
        writer.appendText("</body></html>\n")
    }
    fun getResult() = filename
}

Main class

BuilderSample.java


public class BuilderSample {
	public static void main(String[] args) {
		if (args.length != 1) {
			usage();
			System.exit(0);
		}
		if (args[0].equals("plain")) {
			TextBuilder textbuilder = new TextBuilder();
			Director director = new Director(textbuilder);
			director.construct();
			String result = textbuilder.getResult();
			System.out.println(result);
		} else if (args[0].equals("html")) {
			HTMLBuilder htmlbuilder = new HTMLBuilder();
			Director director = new Director(htmlbuilder);
			director.construct();
			String filename = htmlbuilder.getResult();
			System.out.println(String.format("%s has been created.", filename));
		} else {
			usage();
			System.exit(0);
		}
	}
	public static void usage() {
		System.out.println("Usage:java Main plain Document creation in plain text");
		System.out.println("Usage:java Main html Document creation with HTML file");
	}
}

BuilderSample.kt


fun main(args: Array<String>) {
    if (args.size != 1){
        usage()
        System.exit(0)
    }
    if (args[0] == "plain"){
        val textbuilder = TextBuilder()
        val director = Director(textbuilder)
        director.construct()
        val result = textbuilder.getResult()
        println(result)
    } else if (args[0] == "html") {
        val htmlbuilder = HTMLBuilder()
        val director = Director(htmlbuilder)
        director.construct()
        val filename = htmlbuilder.getResult()
        println(filename)
    } else {
        usage()
        System.exit(0)
    }

}
fun usage() {
    println("Usage:java Main plain Document creation in plain text")
    println("Usage:java Main html Document creation with HTML file")
}

plain execution result


================================================
[Greeting]

■ From morning to noon

·Good morning.
·Hello.

■ At night

·Good evening.
·good night.
·goodbye.

================================================

html execution result


Greeting.The html has been created.

Greeting.html


<html><head><title>Greeting</title></head><body>
<h1>Greeting</h1>
<p>From morning to noon</p>
<ul>
<li>Good morning.</li>
<li>Hello.</li>
</ul>
<p>At night</p>
<ul>
<li>Good evening.</li>
<li>good night.</li>
<li>goodbye.</li>
</ul>
</body></html>

Class diagram

image.png

Impressions

  1. In kotlin, String # equals is represented by ==, and I learned to run equals internally and use === if I want to compare references.
  2. I learned that until, which does not count the number of fractions, is suitable when using a collection such as Array in a for statement.
  3. I also learned about String Template, lazy evaluation, and java.io.File # printWriter ().

reference

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

Kotlin – Create File – Examples Android development with Kotlin! Let's hold down the basic syntax What Java programmers find useful in Kotlin [Delay initialization with Kotlin](https://re-engines.com/2018/11/15/Delay initialization with kotlin /) I / O (files, networks, etc.) Kotlin - toString, equals, hashCode

Recommended Posts

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
I wrote a design pattern in kotlin Template edition
I wrote a design pattern in kotlin Prototype
Learn the design pattern "Builder" in Python
Design Pattern #Builder
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.
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 studied about design patterns (personal memo) Part 3 (Prototype pattern, Builder pattern)
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).
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 "Iterator" in Python
[Gang of Four] Design pattern learning --Builder
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