为了账号安全,请及时绑定邮箱和手机立即绑定

Kotlin设计模式实现之创建型设计模式

标签:
Android

创建型

在软件工程中,创建型设计模式是一系列用来处理对象的创建机制的模式,根据实际情况,采取合适的方式创建对象。基础的对象创建方式可能会造成设计问题或增加程序的复杂度。创建型设计模式通过某种方式的控制,来解决对象创建所产生的问题。

建造者模式

建造者模式是用来创建复杂的对象。它同过将组成部分按照相同的顺序或是某种特定的算法进行创建。使用一个外部类来控制构建算法。

举例

    // 我们假设Dialog是由第三方库所提供的
    // 我们只用权限访问Dialog的公共接口,并且不能修改。

    class Dialog() {        fun showTitle() = println("showing title")        fun setTitle(text: String) = println("setting title text $text")        fun setTitleColor(color: String) = println("setting title color $color")        fun showMessage() = println("showing message")        fun setMessage(text: String) = println("setting message $text")        fun setMessageColor(color: String) = println("setting message color $color")        fun showImage(bitmapBytes: ByteArray) = println("showing image with size ${bitmapBytes.size}")        fun show() = println("showing dialog $this")
    }    //建造者:
    class DialogBuilder() {        constructor(init: DialogBuilder.() -> Unit) : this() {
            init()
        }        private var titleHolder: TextView? = null
        private var messageHolder: TextView? = null
        private var imageHolder: File? = null

        fun title(init: TextView.() -> Unit) {
            titleHolder = TextView().apply { init() }
        }        fun message(init: TextView.() -> Unit) {
            messageHolder = TextView().apply { init() }
        }        fun image(init: () -> File) {
            imageHolder = init()
        }        fun build(): Dialog {            val dialog = Dialog()

            titleHolder?.apply {
                dialog.setTitle(text)
                dialog.setTitleColor(color)
                dialog.showTitle()
            }

            messageHolder?.apply {
                dialog.setMessage(text)
                dialog.setMessageColor(color)
                dialog.showMessage()
            }

            imageHolder?.apply {
                dialog.showImage(readBytes())
            }            return dialog
        }        class TextView {            var text: String = ""
            var color: String = "#00000"
        }
    }

使用

    //一个创建dialog建造器和建造Dialog的函数
    fun dialog(init: DialogBuilder.() -> Unit): Dialog {        return DialogBuilder(init).build()
    }    val dialog: Dialog = dialog {
        title {
            text = "Dialog Title"
        }
        message {
            text = "Dialog Message"
            color = "#333333"
        }
        image {
            File.createTempFile("image", "jpg")
        }
    }

    dialog.show()

输出

setting title text Dialog Title
setting title color #00000showing title
setting message Dialog Message
setting message color #333333showing message
showing image with size 0showing dialog Dialog@5f184fc6

<a target="_blank title=" null"="" style="word-wrap: break-word; word-break: break-all;">工厂方法模式

工厂模式用来替换类的构造器,抽象对象的生产过程,所以可以在运行时决定创建哪一类型的对象。

举例

    interface Currency {        val code: String
    }    class Euro(override val code: String = "EUR") : Currency    class UnitedStatesDollar(override val code: String = "USD") : Currency    enum class Country {
        UnitedStates, Spain, UK, Greece
    }    class CurrencyFactory {        fun currencyForCountry(country: Country): Currency? {            when (country) {
                Country.Spain, Country.Greece -> return Euro()
                Country.UnitedStates          -> return UnitedStatesDollar()                else                          -> return null
            }
        }
    }

使用

    val noCurrencyCode = "No Currency Code Available"

    val greeceCode = CurrencyFactory().currencyForCountry(Country.Greece)?.code() ?: noCurrencyCode
    println("Greece currency: $greeceCode")

    val usCode = CurrencyFactory().currencyForCountry(Country.UnitedStates)?.code() ?: noCurrencyCode
    println("US currency: $usCode")

    val ukCode = CurrencyFactory().currencyForCountry(Country.UK)?.code() ?: noCurrencyCode
    println("UK currency: $ukCode")

输出

Greece currency: EUR
US currency: USD
UK currency: No Currency Code Available

<a target="_blank title=" null"="" style="word-wrap: break-word; word-break: break-all;">单例模式

单例模式确保了一个类只能有一个对象实例被创建。所有对单例类对象的引用都指向同一个潜在实例。它很少被用到,不要过度的使用哦!

举例

    object PrinterDriver {
        init {
            println("Initializing with object: $this")
        }        fun print() = println("Printing with object: $this")
    }

使用

    println("Start")
    PrinterDriver.print()
    PrinterDriver.print()

输出

StartInitializing with object: PrinterDriver@6ff3c5b5
Printing with object: PrinterDriver@6ff3c5b5
Printing with object: PrinterDriver@6ff3c5b5

<a target="_blank title=" null"="" style="word-wrap: break-word; word-break: break-all;">抽象工厂模式

抽象工厂模式用来为客户端提供一系列相关或依赖的对象。在运行时决定哪一个对象簇被创建。

举例

    interface Plant

    class OrangePlant : Plant

    class ApplePlant : Plant

    abstract class PlantFactory {        abstract fun makePlant(): Plant        companion object {            inline fun <reified T : Plant> createFactory(): PlantFactory = when (T::class) {
                OrangePlant::class -> OrangeFactory()
                ApplePlant::class  -> AppleFactory()                else               -> throw IllegalArgumentException()
            }
        }
    }    class AppleFactory : PlantFactory() {        override fun makePlant(): Plant = ApplePlant()
    }    class OrangeFactory : PlantFactory() {        override fun makePlant(): Plant = OrangePlant()
    }

使用

    val plantFactory = PlantFactory.createFactory(OrangePlant::class)
    val plant = plantFactory.makePlant()
    println("Created plant: $plant")

输出

    Created plant: OrangePlant@4f023edb

原文链接:http://www.apkbus.com/blog-822717-72702.html

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消