第79讲:单例深入讲解及单例背后的链式表达式

来源:互联网 发布:java float 比较相等 编辑:程序博客网 时间:2024/05/29 03:21

在Scala中,表达单例的一种语法,就是object对象,如果此对象有伴生类的话,此对象就是伴生对象,被用作公共方法或者成员字段的存储区。

其实每一个对象都有单例类型,如:

/** * 单例深入讲解及单例背后的链式表达式 * Created by zhiwang on 2015/8/9. */import scala.reflect.runtime.universe._object Scala1class Java1class JVM {  def method1: this.type = this}class JVM_Language extends JVM {  def method2: this.type  = this}object Type_Advanced {  def main(args: Array[String]) {    println(Scala1.getClass)    println(typeOf[Scala1.type])    val java1 = new Java1    val java2 = new Java1    println(typeOf[java1.type])    println(typeOf[java2.type])    val conent: java1.type = java1    val jvm = new JVM_Language    jvm.method1.method2  }}

运行结果:
class com.ifly.edu.scala.BestPractice.Scala1$
com.ifly.edu.scala.BestPractice.Scala1.type
java1.type
java2.type

从上面运行结果看,不管是 object Scala1 ,还是 val java1 = new Java1,val java2 = new Java1,都有一个.type 的type对象,并且是唯一的。

所以每个对象都有 单例对象,并且是唯一的

基于object 的这个特性,scala 中的链式表达式就可以轻松搞定
示例代码:

class JVM {  def method1: this.type = this}class JVM_Language extends JVM {  def method2: this.type  = this}

使用方法,
val jvm = new JVM_Language
jvm.method1.method2

参考资料:

百度网盘:http://pan.baidu.com/share/home?uk=4013289088#category/type=0
微信号:18610086859
DT大数据微信公众账号:DT_Spark
DT大数据梦工厂交流群:① 462923555 ②418110145 ③437123764

0 0