Visitor:kotlin

気を付けたこと

  • kotlinではpublicなクラスを一つのファイルに複数書けるのでMain.ktにすべてまとめた
  • FileTreatmentExceptionのコンストラクタ引数に規定値構文を使った
  • dirにEntryのリストを入れるときにEntry型を指定する
  • 追加(add)する配列のときはarrayListOfを使う
  • Fileクラスを使うときにコード補完で勝手にjava.ioをインポートして面倒だった
  • 文字列リテラル内に${変数}で変数を埋め込める
  • $変数というように{}を使わない場合は変数名の後にスペースが必要らしい

import java.lang.RuntimeException
import javax.naming.spi.DirectoryManager

fun main() {
    try {
        println("Making root entries...")
        val rootdir = Directory("root")
        val bindir = Directory("bin")
        val tmpdir = Directory("tmp")
        val usrdir = Directory("usr")
        rootdir.add(bindir)
        rootdir.add(tmpdir)
        rootdir.add(usrdir)
        bindir.add(File("vi", 10000))
        bindir.add(File("latex", 20000))
        rootdir.accept(ListVisitor())
        println("")
        println("Making user entries...")
        val yuki = Directory("yuki")
        val hanako = Directory("hanako")
        val tomura = Directory("tomura")
        usrdir.add(yuki)
        usrdir.add(hanako)
        usrdir.add(tomura)
        yuki.add(File("diary.html", 100))
        yuki.add(File("composiite.java", 200))
        hanako.add(File("memot.tex", 300))
        tomura.add(File("game.doc", 400))
        tomura.add(File("junk.mail", 500))
        rootdir.accept(ListVisitor())


    } catch (e: FileTreatmentException) {
        e.printStackTrace()
    }
}
abstract class Visitor{
    abstract fun visit(file: File)
    abstract fun visit(directory:Directory)
}
interface Element{
    abstract fun accept(v:Visitor)
}
abstract class Entry : Element {
    abstract fun getName():String?
    abstract fun getSize(): Int
    open fun add (entry:Entry):Entry{
        throw FileTreatmentException()
    }
    open fun iterator(): Iterator<Entry> {
        throw FileTreatmentException()
    }

    override fun toString(): String {
        return "${getName()}(${getSize()})"
    }
}
class File(private val name:String,private val size:Int) : Entry() {
    override fun getName(): String? {
        return name
    }

    override fun getSize(): Int {
        return size
    }

    override fun accept(v: Visitor) {
        v.visit(this)
    }

}
class Directory(private val name: String) : Entry() {
    private val dir = arrayListOf<Entry>()
    override fun getName(): String? {
        return name
    }
    override fun getSize(): Int {
        var size = 0
        val it = dir.iterator()
        while (it.hasNext()) {
            val entry = it.next()
            size += entry.getSize()

        }
        return size
    }
    override fun accept(v: Visitor) {
        v.visit(this)
    }
    override fun iterator(): Iterator<Entry> {
        return dir.iterator()
    }
    override fun add(entry: Entry): Entry {
        dir.add(entry)
        return this
    }
}
class ListVisitor : Visitor (){
    private var currentdir = ""
    override fun visit(file: File) {
        println("${currentdir}\\${file}")

    }

    override fun visit(directory: Directory) {
        println("${currentdir}\\${directory}")
        val savedir = currentdir
        currentdir = "${currentdir}\\${directory.getName()}"
        val it = directory.iterator()
        while (it.hasNext()) {
            val entry = it.next()
            entry.accept(this)
        }
        currentdir = savedir
    }
}
class FileTreatmentException(msg:String = "") : RuntimeException(msg) {

}

元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクは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をコピーしました