LoginSignup
0
0

More than 3 years have passed since last update.

Kotlinと図で学んでみるデザインパターン -2章 Adapterパターン-

Last updated at Posted at 2019-09-15

Adapterパターン

既に供給されているclassを、あるもの(新しいAPIなど)に対して最適な形に形成して提供する。
100Vの電源タップから、アダプターを介し、12Vの電源を使用するイメージ。

継承

Adapter Diagram (1).png

open class Banner(private val string: String) {

    fun showWithParen() {
        println("($string)")
    }

    fun showWithAster() {
        println("*$string*")
    }
}
interface Print {
    fun printWeak()
    fun printStrong()
}
class PrintBanner(string: String) : Banner(string), Print {
    override fun printWeak() {
        showWithParen()
    }

    override fun printStrong() {
        showWithAster()
    }
}

移譲

Adapter Diagram (3).png

abstract class Print2 {
    abstract fun printWeak()
    abstract fun printStrong()
}
class PrintBanner2(private val string: String) : Print2() {

    private var banner: Banner = Banner(string)

    override fun printWeak() {
        banner.showWithParen()
    }

    override fun printStrong() {
        banner.showWithAster()
    }

}
class Banner(private val string: String) {

    fun showWithParen() {
        println("($string)")
    }

    fun showWithAster() {
        println("*$string*")
    }
}

FileProperties ← Adapter → java.utils.Properties

interface FileIO {
    fun readFromFile(fileName: String)

    fun writeToFile(fileName: String)

    fun setValue(key: String, value: String)

    fun getValue(key: String)
}
class FileProperties : Properties(), FileIO {

    override fun readFromFile(fileName: String) {
        load(FileInputStream(fileName))
    }

    override fun writeToFile(fileName: String) {
        store(FileOutputStream(fileName), "written by FileProperties")
    }

    override fun setValue(key: String, value: String) {
        setProperty(key, value)
    }

    override fun getValue(key: String) {
        getProperty(key)
    }
}

main

fun main() {

    val p: Print = PrintBanner("Hello World")
    p.printWeak()
    p.printStrong()

    val f: FileIO = FileProperties()
    try {
        f.readFromFile("src/file.txt")
        f.setValue("year", "2004")
        f.setValue("month", "4")
        f.setValue("day", "21")
        f.writeToFile("newfile.txt")
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

※ Java 言語で学ぶデザインパターン入門をKotlinと図で理解しようとしている学習用アウトプットです。UML書式に沿ってはいません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0