kotlin半生对象

In this tutorial, we’ll look at how Kotlin deals with Singleton Pattern and static properties. We will learn how to create Kotlin Singleton class and what is companion object.

在本教程中,我们将研究Kotlin如何处理Singleton Pattern和静态属性。 我们将学习如何创建Kotlin Singleton类以及什么是伴随对象。

Kotlin·辛格尔顿班 (Kotlin Singleton Class)

A Singleton is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class.

Singleton是一种软件设计模式,可以确保一个类仅具有一个实例,并且该类提供了对其的全局访问点。

Singleton Pattern ensures that only one instance would be created and it would act as a single point of access thereby ensuring thread safety. Following is the generic way to create a Singleton class in Java.

单例模式可确保仅创建一个实例,并将其用作单个访问点,从而确保线程安全。 以下是在Java中创建Singleton类的通用方法。

public class Singleton {private static Singleton instance = null;private Singleton(){}private synchronized static void createInstance() {if (instance == null) {instance = new Singleton();}}public static Singleton getInstance() {if (instance == null) createInstance();return instance;}}

The synchronized keyword ensures that there are no thread interferences when creating the instance.

synchronized关键字可确保创建实例时没有线程干扰。

The Kotlin equivalent of the above code is given below.

上面代码的Kotlin等效项如下所示。

object Singleton

Yes, that’s it for creating a singleton class in Kotlin.

是的,就是在Kotlin中创建单例类。

Kotlin对象声明 (Kotlin object Declaration)

  • Kotlin’s representation of a Singleton class requires the object keyword only.Kotlin对Singleton类的表示仅需要object关键字。
  • Hence a Singleton class in Kotlin can be defined without the use of a class.因此,可以在不使用类的情况下定义Kotlin中的Singleton类。
  • An object class can contain properties, functions and the init method.object类可以包含属性,函数和init方法。
  • The constructor method is NOT allowed.不允许使用构造方法。
  • A singleton object can be defined inside a class. It cannot be defined inside an inner class.可以在类内部定义单例对象。 不能在内部类中定义。
  • An object cannot be instantiated in the way a class is instantiated.不能以实例化类的方式实例化对象。
  • An object gets instantiated when it is used for the first time.首次使用对象时,将实例化该对象。

Let’s see a basic implementation of an object in Kotlin.

让我们看一下Kotlin中object的基本实现。

object Singletonfun main(args: Array<String>) {print(Singleton.javaClass)
}//Following is printed in the console.
//class Singleton

The javaClass is auto-generated by the singleton class and prints the equivalent name for the Java class name.

javaClass由单例类自动生成,并打印与Java类名称相同的名称。

Let’s add a function and properties in the object singleton class.

让我们在object单例类中添加一个函数和属性。

object Singleton
{init {println("Singleton class invoked.")}var name = "Kotlin Objects"fun printName(){println(name)}}fun main(args: Array<String>) {Singleton.printName()Singleton.name = "KK"var a = A()
}class A {init {println("Class init method. Singleton name property : ${Singleton.name}")Singleton.printName()}
}//Following is printed in the console.
//Singleton class invoked.
//Kotlin Objects
//Class init method. Singleton name property : KK
//KK

In the above code, the changes in the object class are reflected when the class A is instantiated.

在上面的代码中,实例化class A时反映了对象类中的更改。

Object initialization is similar to lazy initialization of kotlin properties. In the below code, object isn’t initialized since it isn’t used.

对象初始化类似于kotlin属性的惰性初始化。 在下面的代码中, object未初始化,因为未使用它。

class A {object Singleton{init {println("Singleton class invoked.")}var name = "Kotlin Objects"fun printName(){println(name)}}init {println("Class init method. Singleton name property")}
}//Console:
//Class init method

Objects have much more to use than just being a Singleton class.

对象不仅仅是单例类,还有更多使用对象。

Kotlin对象表达式 (Kotlin Object Expressions)

Objects in Kotlin, can be used as class variants. An object can extend a class, implement an interface.

Kotlin中的对象可用作类的变体。 一个对象可以扩展一个类,实现一个接口。

Let’s look at extending a class in the object to create a variant.

让我们看一下扩展对象中的类以创建变体。

fun main(args: Array<String>) {var a = A()Singleton.printName()
}open class A {open fun printName() {print("This is class A")}init {println("Class init method.")}
}object Singleton : A() {init {println("Singleton class invoked.")}var name = "Kotlin Objects"override fun printName() {println(name)}
}//Console Output:
//Class init method.
//Class init method.
//Singleton class invoked.
//Kotlin Objects

We’ve defined the class and function printName() as open since they would be subclassed and overridden respectively.

我们将类和函数printName()定义为open因为它们将分别被子类化和覆盖。

Unarguably, the init function of the class is called twice. Thus we are able to able to create an anonymous class in Kotlin using the above method.

无疑,该类的init函数被调用了两次。 因此,我们能够使用上述方法在Kotlin中创建一个匿名类。

Objects can have superclasses.

对象可以具有超类。

Kotlin伴侣对象 (Kotlin Companion Object)

  • Kotlin doesn’t have static keyword. So how do we set static variables and methods?Kotlin没有static关键字。 那么我们如何设置静态变量和方法呢?
  • companion object is the answer. It is equivalent to static objects in Java.companion object就是答案。 它等效于Java中的static对象。
  • A companion object is common to all instances of the classes. It can access all members of the class too, including the private constructors.companion object是所有类实例共有的。 它也可以访问该类的所有成员,包括私有构造函数。
  • A companion object is initialized when the class is instantiated.实例化类时,将初始化一个伴随对象。
  • A companion object CANNOT be declared outside the class.不能在类外部声明伴随对象。

Let’s look at a simple example of kotlin companion object.

让我们看一个简单的kotlin伴随对象示例。

fun main(args: Array<String>) {var a = A.nameA.name = "Kotlin Tutorials"A.printName() //prints Kotlin Tutorials
}class A {companion object Singleton{init {println("Singleton class invoked.")}var name = "Kotlin Objects"fun printName(){println(name)}}init {println("Class init method.")}
}

Members of the companion object are called by using the class name as the qualifier.

通过使用类名称作为限定符来调用伴随对象的成员。

We can omit the companion object name too. In that case Companion name can be used to call the Singleton object.

我们也可以省略伴随对象的名称。 在这种情况下,可以使用Companion名称来调用Singleton对象。

fun main(args: Array<String>) {A.CompanionA.Companion.name = "Kotlin Tutorials"A.printName() //prints Kotlin Tutorials
}class A {companion object{init {println("Singleton class invoked.")}var name = "Kotlin Objects"fun printName(){println(name)}}init {println("Class init method.")}
}

Note: object isn’t instantiated until it is called. companion object is instantiated as soon as the class is as shown in the below code.

注意: object直到被调用才实例化。 该类一如下面的代码所示,实例化companion object

fun main(args: Array<String>) {var a = A()
}class A {companion object SingletonB {init {println("SingletonB class invoked.")}}object SingletonA {init {println("SingletonA class invoked.")}}init {println("Class init method.")}
}//Following is printed in the console.
//SingletonB class invoked.
//Class init method.

Notice that the init of object wasn’t called. This brings an end to kotlin singleton and companion object example tutorial.

注意object的初始化没有被调用。 这样就结束了kotlin单例和伴侣对象示例教程。

Reference:Kotlin Docs

参考: Kotlin文档

翻译自: https://www.journaldev.com/18662/kotlin-singleton-companion-object

kotlin半生对象

kotlin半生对象_Kotlin单一对象,Kotlin伴侣对象相关推荐

  1. kotlin半生对象_Kotlin程序| 随播对象特征

    kotlin半生对象 伴侣对象 (Companion object) If you need a function or a property to be tied to a class rather ...

  2. kotlin半生对象_如何在Kotlin中使用Actor实现对象池

    kotlin半生对象 by osha1 由osha1 如何在Kotlin中使用Actor实现对象池 (How to implement an Object-Pool with an Actor in ...

  3. scala什么是单例对象_Scala单例和伴侣对象

    scala什么是单例对象 Scala中的单例对象 (Singleton objects in Scala) Scala being an object-oriented programming lan ...

  4. 在kotlin companion object中读取Bean,注入Bean对象

    在kotlin companion object中读取Bean,注入Bean对象 在使用kotlin时,或多或少地会使用到一些公共组件,如 http. mongo. redis相关的组件.   使用组 ...

  5. kotlin将对象转换为map_在 Kotlin 的 data class 中使用 MapStruct

    原文:https://zhuanlan.zhihu.com/p/208525542 一. data class 的 copy() 为浅拷贝 浅拷贝是按位拷贝对象,它会创建一个新对象,这个对象有着原始对 ...

  6. Kotlin学习笔记 第二章 类与对象 第十二 十三节 对象表达式与对象声明 类型别名

    参考链接 Kotlin官方文档 https://kotlinlang.org/docs/home.html 中文网站 https://www.kotlincn.net/docs/reference/p ...

  7. java kotlin相互调用_Kotlin的互操作——Kotlin与Java互相调用

    原标题:Kotlin的互操作--Kotlin与Java互相调用 互操作就是在Kotlin中可以调用其他编程语言的接口,只要它们开放了接口,Kotlin就可以调用其成员属性和成员方法,这是其他编程语言所 ...

  8. kotlin和java差别_Kotlin和Java的常用方法的区别总结

    一.kotlin和java的常用语法区别 1).类.public class.public final class java 1 2public final class User{ } 1 2publ ...

  9. kotlin 读取json文件_Kotlin数据类及json解析

    通过数据类,可以方便地得到很多有趣的函数,一部分是来自属性,比如编写getter和setter函数,还有下面这些函数:equals(): 比较两个对象的属性来确保他们是相同的. hashCode(): ...

最新文章

  1. 三维点云对应关系聚合算法的性能评价
  2. fedora利用vmlinuz和initrd制作linux启动u盘,Fedora 17的U盘安装方法
  3. 居民身份证号码的奥秘及身份证第18位(校验码)的计算方法
  4. ASP.NET Web Pages:Chart 帮助器
  5. LeetCode 520. 检测大写字母
  6. 关于MySQL存储过程异常处理的一点心得
  7. Python入门--字符串的判断操作
  8. MLP多层感知机原理简介+代码详解
  9. TED如何掌控你的时间(第二天)
  10. Qt使用paintevent事件绘制图像(可进行缩放且能够局部放大)
  11. Beini奶瓶U盘PE完整教程[2018-11-28]
  12. 修图类APP原型设计分享– Hello Camera
  13. 每日一题:1.function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastNa
  14. 常用设计模式——装饰者模式
  15. 【山无遮,海无拦】LeetCode题集 线性枚举之最值算法
  16. 极度未知HyperX20周年盛惠—HyperX Cloud 2 飓风FPS耳机听音辨位
  17. 【论文阅读】【3d目标检测】Embracing Single Stride 3D Object Detector with Sparse Transformer
  18. Oracle索引与where
  19. MIPS 、DMIPS、MFLOPS、petaflop、teraflop
  20. VC6中工具条的新特色 (转)

热门文章

  1. 【转】OCaml基础知识
  2. C++两种编写单件模式方法对比
  3. [转载] python中字典copy_python深度复制字典,copy方法与deepcopy方法
  4. [转载] Python基于机器学习方法实现的电影推荐系统
  5. [转载] 6.3 cmath--数学函数
  6. [转载] 重新抛出异常与 public Throwable fillInStackTrace()
  7. [转载] python在内网服务器安装第三方库
  8. 下载EPM包详细运行日志
  9. Spring boot 学习二:入门
  10. 如何使用TreeView控件