标签:string div 实例化 默认值 tostring new test 静态 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
scala 基础十二 scala apply的使用,工厂方法和单例模式的实现
标签:string div 实例化 默认值 tostring new test 静态 apply
原文地址:http://www.cnblogs.com/IChing/p/7115319.html