scala 基础十二 scala apply的使用,工厂方法和单例模式的实现

1. apply 可以用来实现类似于静态的初始化类的实例,请看下面实例

package smart.iot

class applyclass {
  
}

class A
{
    def apply()=println("hello class A");
}


object B
{
  def apply()=println("hello object B");
}


object applyRun
{
  def main(args: Array[String]): Unit = {
    
     //显示的调用 apply 方法
     B.apply()
     //直接加括号 也可以调用appy方法
     B();
    
     //实例化一个类A
    var a= new A()
    //显示调用 apply方法
     a.apply()
     //
     a()
  }
}


result:
hello object B
hello object B
hello class A
hello class A

 2.用apply实现工厂方法, 用apply对象静态的去实现 其他的类。不明白的请看示列

package smart.iot

class applyclass {
  
}

class A
{
    def test()=println("function test")
    def apply()=println("hello class A");
}


object B
{
  def apply()=println("hello object B");
}

//类似一个工厂方法,用C的apply 方法去实例化A
object C
{
  def apply()=new A()
}


object applyRun
{
  def main(args: Array[String]): Unit = {
    

    
   //类似于定义一个静态的方法初始化 ,用C去引用A的方法
   var  c=C()
   c.apply()
   c.test()
  }
}

 

3.用apply实现单例模式,下面我们来做一个测试。 分别用 c 和 c1引用伴生对象C

package smart.iot

class applyclass {
  
}

class A
{
    def test()=println("function test")
    def apply()=println("hello class A");
}


object B
{
  def apply()=println("hello object B");
}

//类似一个工厂方法,用C的apply 方法去实例化A
object C
{
  def apply()=new A()
}


object applyRun
{

    var  c=C()
    println(c.toString)
    var c1=C()
    println(c1.toString)
  }
}


result:
smart.iot.A@7d4991ad
smart.iot.A@28d93b30

 这样我们获取的其实是两个对象,每次应用C 都会实例化一些新的A对象,下面我们把它改成一个单例模式

package smart.iot

class applyclass {
  
}

class A
{
    def test()=println("function test")
    def apply()=println("hello class A");
}


object B
{
  def apply()=println("hello object B");
}

//类似一个工厂方法,用C的apply 方法去实例化A
object C
{
  //定义一个A对象 给一个默认值
  var a:A=_
  //如果a 被实现,new 一下A 如果已经实现了 就直接返回A 这样就实现了单利模式
  def apply()=if(a==null){a=new A();a}else a
}


object applyRun
{
  def main(args: Array[String]): Unit = {

  
    var  c=C()
    println(c.toString)
    var c1=C()
    println(c1.toString)
  }
}


result:
smart.iot.A@7d4991ad
smart.iot.A@7d4991ad

 

转载于:https://www.cnblogs.com/IChing/p/7115319.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值