设计模式之Kotlin

创建型

工厂方法模式

interface Product {
    val name: String
}

class ProductA(override val name: String = "ProductA") : Product
class ProductB(override val name: String = "ProductB") : Product

interface Factory {
    fun makeProduct(): Product
}

class FactoryA : Factory {
    override fun makeProduct() = ProductA()
}
class FactoryB : Factory {
    override fun makeProduct() = ProductB()
}

抽象工厂模式

class SeriesATextView(context: Context?) : TextView(context)
class SeriesBTextView(context: Context?) : TextView(context)

class SeriesAButton(context: Context?) : Button(context)
class SeriesBButton(context: Context?) : Button(context)

interface AbstractFactory {
    val context: Context?
    fun makeTextView(): TextView
    fun makeButton(): Button
}

class SeriesAFactory(override val context: Context?) : AbstractFactory {
    override fun makeTextView() = SeriesATextView(context)
    override fun makeButton() = SeriesAButton(context)
}

class SeriesBFactory(override val context: Context?) : AbstractFactory {
    override fun makeTextView() = SeriesBTextView(context)
    override fun makeButton() = SeriesBButton(context)
}

建造者模式

class Car (
    val model: String?,
    val year: Int
) {
    private constructor(builder: Builder) : this(builder.model, builder.year)

    class Builder {
        var model: String? = null
        var year: Int = -1

        fun build() = Car(this)
    }

    companion object {
        inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build()
    }
}

// usage
val car = Car.build { 
    model = "John One"
    year = 2017
}

原型模式

data class EMail(var recipient: String, var subject: String?, var message: String?)

val mail = EMail("abc@example.com", "Hello", "Don't know what to write.")
val copy = mail.copy(recipient = "other@example.com")

单例模式

使用 object 实现

结构型模式

适配器模式

interface Target {
    fun request()
}

interface Adaptee {
    fun ask()
}

class Adapter(val wrapper: Adaptee) : Target {
    override fun request() {
        wrapper.ask()
    }
}

桥接模式

interface Color {
    fun coloring();
}

class RedColor : Color { ... }
class BlueColor : Color { ... }

interface Pen {
    val colorImpl: Color    // this is bridge
    fun write()
}

class BigPen(override val colorImpl: Color) : Pen { ... }
class SmallPen(override val colorImpl: Color) : Pen { ... }

组合模式

interface AbstractFile {    // Component
    var childCount: Int
    fun getChild(i: Int): AbstractFile
    fun size(): Long
}

class File(val size: Long, override var childCount: Int = 0) : AbstractFile {
    override fun getChild(i: Int): AbstractFile {
        throw RuntimeException("You shouldn't call the method in File")
    }

    override fun size() = size
}

class Folder(override var childCount: Int) : AbstractFile {
    override fun getChild(i: Int): AbstractFile {
        ...
    }

    override fun size(): Long {
        return (0..childCount)
                .map { getChild(it).size() }
                .sum()
    }
}

装饰模式

class Text(val text: String) {
    fun draw() = print(text)
}

fun Text.underline(decorated: Text.() -> Unit) {
    print("_")
    this.decorated()
    print("_")
}

// usage
Text("Hello").run {
    underline {
        draw()
    }
}

外观模式

class ComplexSystemStore(val filePath: String) {
    init {
        println("Reading data from file: $filePath")
    }

    val store = HashMap<String, String>()

    fun store(key: String, payload: String) {
        store.put(key, payload)
    }

    fun read(key: String): String = store[key] ?: ""

    fun commit() = println("Storing cached data: $store to file: $filePath")
}

data class User(val login: String)

//Facade:
class UserRepository {
    val systemPreferences = ComplexSystemStore("/data/default.prefs")

    fun save(user: User) {
        systemPreferences.store("USER_KEY", user.login)
        systemPreferences.commit()
    }

    fun findFirst(): User = User(systemPreferences.read("USER_KEY"))
}

// usage
val userRepository = UserRepository()
val user = User("dbacinski")
userRepository.save(user)
val resultUser = userRepository.findFirst()

享元模式

enum class Color {
    black, white
}

open class Chess(val color: Color) { 
    fun display(pos: Pair<Int, Int>) {
        println("The $color chess at position $pos")
    }
}

class BlackChess : Chess(color = Color.black)
class WhiteChess : Chess(color = Color.white)

object ChessFactory {
    private val table = Hashtable<Color, Chess>()
    
    init {
        table.put(Color.black, BlackChess())
        table.put(Color.white, WhiteChess())
    }
    
    fun getChess(color: Color) = table[color]!!
}

// usage
val blackChess = ChessFactory.getChess(Color.black)
val whiteChess = ChessFactory.getChess(Color.white)
blackChess.display(Pair(9, 5))
whiteChess.display(Pair(5, 9))
whiteChess.display(Pair(2, 3))

代理模式

interface File {
    fun read(name: String)
}

class NormalFile : File {
    override fun read(name: String) = println("Reading file: $name")
}

// proxy
class SecuredFile : File {
    val normalFile = NormalFile()
    var password: String = ""

    override fun read(name: String) {
        if (password == "secret") {
            println("Password is correct: $password")
            normalFile.read(name)   // call target object behavior
        } else {
            println("Incorrect password. Access denied!")
        }
    }
}

行为型模式

职责链模式

interface EventHandler {
    var next: EventHandler?
    fun handle(event: MotionEvent): Boolean
}

open class View : EventHandler {
    override var next: EventHandler? = null
    override fun handle(event: MotionEvent): Boolean {
        return onTouchEvent()
    }
    open fun onTouchEvent() : Boolean { 
        ...
        return false 
    }
}

open class ViewGroup : View() {
    override fun handle(event: MotionEvent): Boolean {
        if (onInterceptTouchEvent(event)) return onTouchEvent()
        else return next?.handle(event)!!
    }
    
    open fun onInterceptTouchEvent(event: MotionEvent): Boolean { // 是否拦截事件
        ...
        return false
    }
}

命令模式

interface Command {
    var value: Int
    val param: Int
    fun execute()
    fun undo()
}

class AddCommand(override var value: Int, override val param: Int) : Command {
    override fun execute() {
        value += param
        println("execute add command and value:$value")
    }
    override fun undo() {
        value -= param
        println("undo add command and value:$value")
    }
}

class MultiplyCommand(override var value: Int, override val param: Int) : Command {
    override fun execute() {
        value *= param
        println("execute multiply command and value:$value")
    }
    override fun undo() {
        value /= param
        println("undo multiply command and value:$value")
    }
}

class Calculator {
    val queue = mutableListOf<Command>()
    fun compute(command: Command) {
        command.execute()
        queue.add(command)
    }
    fun undo() {
        queue.lastOrNull()?.undo()
        queue.removeAt(queue.lastIndex)
    }
}

解释器模式

待完善

迭代器模式

class Sentence(val words: List<String>)

operator fun Sentence.iterator(): Iterator<String> = words.iterator()
// or
operator fun Sentence.iterator(): Iterator<String> = object : Iterator<String> {
    val iterator = words.iterator()
    
    override fun hasNext() = iterator.hasNext()

    override fun next() = iterator.next()
}

中介者模式

interface ChatMediator {
    fun sendMsg(msg: String, user: User)
    fun addUser(user: User)
}

abstract class User(val name: String, val mediator: ChatMediator) {
    abstract fun send(msg: String)
    abstract fun receive(msg: String)
}

class ChatMediatorImpl : ChatMediator {
    private val users = mutableListOf<User>()

    override fun sendMsg(msg: String, user: User) {
        users.filter { it != user }
                .forEach { it.receive(msg) }
    }

    override fun addUser(user: User) {
        users.add(user)
    }
}

class UserImpl(name: String, mediator: ChatMediator) : User(name, mediator) {
    override fun send(msg: String) {
        println("$name : sending messages = $msg")
        mediator.sendMsg(msg, this)
    }

    override fun receive(msg: String) {
        println("$name : received messages = $msg")
    }
}

备忘录模式

data class Memento(val fileName: String, val content: StringBuilder)

class FileWriter(var fileName: String) {
    
    private var content = StringBuilder()
    
    fun write(str: String) {
        content.append(str)
    }
    
    fun save() = Memento(fileName, StringBuilder(content))
    
    fun restore(m: Memento) {
        fileName = m.fileName
        content = m.content
    } 
}

观察者模式

interface TextChangedListener {
    fun onTextChanged(newText: String)
}

class TextView {
    var listener: TextChangedListener? = null

    var text: String by Delegates.observable("") { prop, old, new ->
        listener?.onTextChanged(new)
    }
}

状态模式

sealed class UserState(val name:String, val isAuthorized: Boolean) {
    abstract fun click()

    class Unauthorized : UserState(name = "Unauthorized", isAuthorized = false) {
        override fun click() {
            print("User is unauthorized.")
        }
    }

    class Authorized(name: String) : UserState(name, isAuthorized = true) {
        override fun click() {
            print("User is authorized as $name")
        }
    }
}

class User {
    private var state: UserState = UserState.Unauthorized()
    
    val name: String
        get() = state.name
    
    val isAuthorized: Boolean
        get() = state.isAuthorized
    
    fun click() = state.click()
    
    fun login(name: String) {
        state = UserState.Authorized(name)
    }
    
    fun logout() {
        state = UserState.Unauthorized()
    }
}

策略模式

class Customer(val name: String, val fee: Double, val discount: (Double) -> Double) {
    fun pricePerMonth() = discount(fee)
}

// usage
val studentDiscount = { fee: Double -> fee/2 }
val noDiscount = { fee: Double -> fee }

val student = Customer("Ned", 10.0, studentDiscount)
val regular = Customer("John", 10.0, noDiscount)

模版方法模式

class Task {
    fun run(step2: () -> Unit, step3: () -> Unit) {
        step1()
        step2()
        step3()
    }
    
    fun step1() { ... }
}

访问者模式

interface Employee {
    fun accept(visitor: Visitor)
}

class GeneralEmployee(val wage: Int) : Employee {
    override fun accept(visitor: Visitor) = visitor.visit(this)

}

class ManagerEmployee(val wage: Int, val bonus: Int) : Employee {
    override fun accept(visitor: Visitor) = visitor.visit(this)
}

interface Visitor {
    fun visit(ge: GeneralEmployee)
    fun visit(me: ManagerEmployee)
}

class FADVisitor : Visitor {
    override fun visit(ge: GeneralEmployee) {
        println("GeneralEmployee wage:${ge.wage}")
    }
    override fun visit(me: ManagerEmployee) {
        println("ManagerEmployee wage:${me.wage + me.bonus}")
    }
}
// other visitor ...

参考:Kotlin 语言下设计模式的不同实现.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值