Builder:kotlin

気を付けたこと

  • kotlinでは複数のクラスを一つのファイルにまとめることが出来るのでまとめた
  • 文字列リテラル内で”${式}”のようにすることで変数や式を直接埋め込める
  • 配列を作るときはarrayOf()を使う

import java.io.FileWriter
import java.io.IOException
import java.io.PrintWriter
import kotlin.system.exitProcess

fun main(args: Array<String>) {
    if (args.size != 1) {
        usage()
        exitProcess(0)
    }
    if (args[0].equals("plain")) {
        val textBuilder = TextBuilder()
        val director = Director(textBuilder)
        director.construct()
        val result = textBuilder.getResult()
        println(result)
    }else if (args[0].equals("html")) {
        val htmlBuilder = HTMLBuilder()
        val director = Director(htmlBuilder)
        director.construct()
        val filename = htmlBuilder.getResult()
        println("${filename}が作成されました")

    } else {
        usage()
        exitProcess(0)
    }
}
fun usage() {
    println("Usage: java Main plain")
    println("Usage: java Main html")
}
abstract class Builder {
    abstract fun makeTitle(title: String)
    abstract fun makeString(str: String)
    abstract fun makeItems(items: Array<String>)
    abstract fun close()
}
class Director(private val builder: Builder) {
    fun construct() {
        builder.makeTitle("Greeting")
        builder.makeString("朝から昼にかけて")
        builder.makeItems(arrayOf("おはようございます。", "こんにちは"))
        builder.makeString("夜に")
        builder.makeItems(arrayOf("こんばんは", "おやすみなさい", "さようなら"))
        builder.close()
    }

}
class TextBuilder : Builder() {
    private val 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 in 0 until items.size) {
            buffer.append("  :${items[i]}\n")
        }
        buffer.append("\n")
    }

    override fun close() {
        buffer.append("=======================\n")
    }
    fun getResult(): String {
        return buffer.toString()
    }

}
class HTMLBuilder : Builder() {
    private var filename = ""
    private var writer: PrintWriter? = null
    override fun makeTitle(title: String) {
        filename = "${title}.html"
        try {
            writer = PrintWriter(FileWriter(filename))
        } catch (e: IOException) {
            e.printStackTrace()
        }
        writer?.println("<html><head><title>${title}</title></head><body>")
        writer?.println("<h1>${title}</h1>")

    }

    override fun makeString(str: String) {
        writer?.println("<p>${str}</p>")
    }

    override fun makeItems(items: Array<String>) {
        writer?.println("<ul>")
        for (i in items.indices) {
            writer?.println("<li>${items[i]}</li>")
        }
        writer?.println("</ul>")
    }

    override fun close() {
        writer?.println("</body></html>")
        writer?.close()
    }
    fun getResult():String {
        return filename

    }
}

元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクはAmazonアソシエイトを使用しています。

増補改訂版Java言語で学ぶデザインパターン入門

ライセンス表記

Copyright (C) 2001,2004 Hiroshi Yuki.

hyuki@hyuki.com
This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.

コメント

タイトルとURLをコピーしました