Command:kotln

気を付けたこと

  • kotlinでは複数のクラスを一つのファイルにまとめることが出来るのでまとめた
  • main関数をMainクラスではなくトップとして宣言した
  • 引数にnullable型があるものを使うときは!!を使ったりしたがnullの場合は実行時にエラーになる

パッケージ

kotlinでは「packageprivate」のアクセス修飾子は無いです。代わりに「internal」があります。同じモジュールからのみアクセスできます。別にモジュールに分けなくてもpackageキーワードは使えますが、internalを使えるので分けといた方が良い気がします。あとjavaのようにフォルダ名とパッケージ名が一致している必要は無いみたいですが、javaと合わせておいた方が良い気がします。こちらが参考になりました。

Intellijでモジュールを追加する

追加したいフォルダを右クリックして新規➡モジュール。

ダイアログに従ってモジュール名を決めて作成する。

モジュールの依存関係を追加する

使用する側のクラスが含まれるフォルダを選択してf4キー(ファイル➡モジュールを追加)を押下。

依存関係タブの+ボタンを押して追加したいモジュールを選択。


Main.kt

import command.MacroCommand
import drawer.DdrawCanvas
import drawer.DrawCommand
import java.awt.Canvas
import java.awt.event.*
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.JButton
import javax.swing.JFrame
import kotlin.system.exitProcess

fun main(args: Array<String>) {
    Main("Command Pattern Sample")

}
class Main(title:String):JFrame(title),ActionListener,MouseMotionListener,WindowListener{
    private val history = MacroCommand()
    private val canvas = DdrawCanvas(400, 400, history)
    private val clearButton = JButton("Clear")
    init {
        this.addWindowListener(this)
        canvas.addMouseMotionListener(this)
        clearButton.addActionListener(this)
        val buttonBox = Box(BoxLayout.X_AXIS)
        buttonBox.add(clearButton)
        val mainBox = Box(BoxLayout.Y_AXIS)
        mainBox.add(buttonBox)
        mainBox.add(canvas)
        contentPane.add(mainBox)
        pack()
        show()
    }

    override fun mouseMoved(e: MouseEvent?) {
    }

    override fun mouseDragged(e: MouseEvent?) {
        val cmd = DrawCommand(canvas, e?.point)
        history.append(cmd)
        cmd.execute()
    }

    override fun windowClosing(e: WindowEvent?) {
        exitProcess(0)
    }

    override fun windowActivated(e: WindowEvent?) {
    }

    override fun windowClosed(e: WindowEvent?) {
    }

    override fun windowDeactivated(e: WindowEvent?) {
    }

    override fun windowDeiconified(e: WindowEvent?) {
    }

    override fun windowIconified(e: WindowEvent?) {
    }

    override fun windowOpened(e: WindowEvent?) {
    }

    override fun actionPerformed(e: ActionEvent?) {
        if (e?.source == clearButton) {
            history.clear()
            canvas.repaint()
        }
    }

}

Drawer.kt

package drawer

import command.Command
import command.MacroCommand
import java.awt.Canvas
import java.awt.Color
import java.awt.Graphics
import java.awt.Point

class DdrawCanvas(width: Int, height: Int, private var history: MacroCommand) : Canvas(), Drawable {
    private var color = Color.red
    private var radius = 6
    init {
        setSize(width, height)
        background = Color.white
        this.history = history

    }

    override fun paint(g: Graphics?) {
        history.execute()
    }

    override fun draw(x: Int, y: Int) {
        val g = graphics
        g.color = this.color
        g.fillOval(x - radius,y - radius,radius * 2,radius * 2)
    }
}
class DrawCommand(private val drawable: Drawable, private val position: Point?):Command{
    override fun execute() {
        drawable.draw(position!!.x,position.y)
    }

}
interface Drawable {
    abstract fun draw(x:Int,y:Int)
}

Command.kt

package command

import java.util.*

interface Command{
    abstract fun execute()
}
class MacroCommand:Command{
    private val commands = Stack<Command>()
    override fun execute() {
        val it = commands.iterator()
        while (it.hasNext()) {
            it.next().execute()
        }

    }
    fun append(cmd: Command) {
        if (cmd != this) {
            commands.push(cmd)
        }
    }
    fun undo() {
        if (!commands.empty()) {
            commands.pop()
        }
    }
    fun clear() {
        commands.clear()
    }
}

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