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.
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.
- Include one title
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()
}
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()
}
}
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
.
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()
}
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
}
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>
==
, and I learned to run equals internally and use ===
if I want to compare references.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