美文网首页
设计模式之创建型模式(Kotlin版)

设计模式之创建型模式(Kotlin版)

作者: ZoranLee | 来源:发表于2021-11-11 15:28 被阅读0次

主要用途:

  • 创建对象

Kotlin中几种最主流的创建型设计模式:

  • 工厂方法模式、抽象工厂模式以及构建者模式。

伴生对象增强工厂模式

简单工厂、工厂方法模式以及抽象工厂

interface Computer {
    val cpu:String
}

//类1
class PC(override val cpu: String = "Core") : Computer

//类2
class Server(override val cpu: String = "Server"):Computer 

//枚举
enum class ComputerType {
    PC,
    Server
}

//工厂类
open class ComputerFactory {

    fun produce(type: ComputerType):Computer{

        return when(type){
            ComputerType.PC->PC()
            ComputerType.Server->Server()
        }
    }
}

//测试方法
fun main(){
    val produce = ComputerFactory().produce(ComputerType.PC)
    print(produce.cpu)
}

重载操作符的改进

object ComputerFactoryOperator{
    // 重载构造操作符
    operator fun invoke (type:ComputerType) :Computer{
        return when(type){
            ComputerType.Server->Server();
            ComputerType.PC->PC();
        }
    }
}

静态工厂方法替换构造函数

interface Computer {
    val cpu:String

    //静态工厂方法替代构造函数
    companion object{
        operator fun invoke(computerType: ComputerType):Computer{
            return when(computerType){
                ComputerType.PC->PC()
                ComputerType.Server->Server()
            }
        }
    }
}

扩展伴生对象方法

 //通过cpu型号 判断电脑类型
fun Computer.Companion.fromCpu(cpu: String): ComputerType? = when (cpu) {
    "Core" -> ComputerType.PC
    "Xeon" -> ComputerType.Server
    else -> null
}

相关文章

  • Kotlin(八)kotlin设计模式-创建型

    创建型模式 - 工厂 Kotlin里面几种主流创建型设计模式:工厂方法模式,抽象工厂模式,构建者模式 8.1 伴生...

  • 设计模式之创建型模式(Kotlin版)

    主要用途: 创建对象 Kotlin中几种最主流的创建型设计模式: 工厂方法模式、抽象工厂模式以及构建者模式。 伴生...

  • 《设计模式之美》- 23种设计模式

    学习《设计模式之美》笔记。 23 种经典设计模式共分为 3 种类型,分别是创建型、结构型和行为型 创建型模式 创建...

  • 23种设计模式总结一

    23 种经典设计模式共分为 3 种类型,分别是创建型、结构型和行为型。 一、创建型设计模式 创建型设计模式包括:单...

  • Java设计模式——生成器模式

    Java设计模式之生成器模式 回顾 这期继续跟大家聊下创建型的设计模式,如果想了解其他创建类的设计模式有哪些,可以...

  • 简单工厂模式

    Android进阶之设计模式 简单工厂模式 简单工厂模式(又叫作静态工厂方法模式), 其属于创建型设计模式,但并不...

  • 设计模式之活学活用的工厂模式

    设计模式之活学活用的工厂模式 工厂模式简介 工厂模式是我们日常开发工作中经常使用的设计模式,它属于创建型设计模式,...

  • 建造者设计模式-Builder design pattern

    建造者设计模式是创建型设计模式的一种。创建型设计模式处理对象创建的问题。 建造者设计模式,用来构建需要经过若干个建...

  • 创建型设计模式总结

    创建型设计模式总结 Intro 前面几篇文章已经把创建型设计模式都介绍了,来做一个简单的总结。 创建型设计模式,就...

  • 单例模式

    单例 单例模式,是一种设计模式,属于创建型设计模式,还有一种创建型设计模式,工厂模式。设计模式总共有23种,三大类...

网友评论

      本文标题:设计模式之创建型模式(Kotlin版)

      本文链接:https://www.haomeiwen.com/subject/yzawzltx.html