気を付けたこと
- kotlinでは複数のクラスを一つのファイルにまとめることが出来るのでまとめた
- staticは無いのでcompanion object{}ブロック内で書く
- syncronizedは関数宣言の先頭に@Syncronizedを付ける
- 配列の初期化はラムダ関数を渡してその中で初期化処理を書く
- javaのようにBigChar[] = new BigChar[10]とかの書き方ではない
- BigString.print()内、配列の要素を回す処理は配列.foreachを使うと楽
文字のテキストファイルはサンプルからコピーしてパスを合わせる必要があります。
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.lang.NullPointerException
import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.size == 0) {
println("Usage:java Main digits")
println("Example: java Main 1212123")
exitProcess(0)
}
val bs = BigString(args[0])
bs.print()
}
class BigChar(private val charname: Char){
private var fontdata: String? = null
init {
try {
val reader = BufferedReader(FileReader("big${charname}.txt"))
//var line :String? = null
val buf = StringBuffer()
//foreach
reader.use{
it.forEachLine {//readLine()
line ->
buf.append(line)
buf.append("\n")
}
}
reader.close()
this.fontdata = buf.toString()
} catch (e: IOException) {
this.fontdata = "${charname}?"
}
}
fun print() {
print(fontdata)
}
}
class BigCharFactory private constructor() {
private val pool = HashMap<String, BigChar>()
companion object {
val singleton = BigCharFactory()
fun getInstance() = singleton
}
@Synchronized fun getBigChar(charname: Char): BigChar {
var bc = pool["${charname}"]
if (bc == null) {
bc = BigChar(charname)
pool["${charname}"] = bc
}
return bc
}
}
class BigString(string: String){
lateinit var bigchars:Array<BigChar>
init {
bigchars = Array<BigChar>(string.length/*配列の要素数*/) {
//配列を初期化する関数を渡す
val factory = BigCharFactory.getInstance()
//@ArrayでArrayの初期化処理に値を返すように指示する
return@Array factory.getBigChar(string[it])
}
}
fun print() {
bigchars.forEach { it.print() }
// for (i in 0 until bigchars.size) {
// bigchars[i].print()
// }
}
}
元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクはAmazonアソシエイトを使用しています。
ライセンス表記
Copyright (C) 2001,2004 Hiroshi Yuki.
hyuki@hyuki.com Java言語で学ぶデザインパターン入門 第3版結城浩『Java言語で学ぶデザインパターン入門 ...
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.
コメント