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: [email protected]
這樣我們獲取的其實是兩個對象,每次應用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: [email protected] [email protected]
scala 基礎十二 scala apply的使用,工廠方法和單例模式的實現