1. Apply can be used to implement an instance of an initialization class similar to static, see the following example
Package Smart.iotclass 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 = { //Display call to apply Method b.apply () //Direct parentheses can also call Appy method B (); Instantiate a Class A var a= new A () //Show Call apply Method a.apply () // A () }}
Result
Hello Object B
Hello Object B
Hello class A
Hello class A
2. Use apply to implement the Factory method, with the Apply object static to implement other classes. If you don't understand, look at the list.
Package Smart.iotclass Applyclass { }class a{ def Test () =println ("function test") def apply () =println (" Hello class A ");} Object b{ def apply () =println ("Hello object B");} Similar to a factory method, use the C apply method to instantiate Aobject c{ def apply () =new A ()}object applyrun{ def main (args:array[string]): Unit = { //similar to defining a static method initialization, using C to refer to a method var c=c () c.apply () c.test () }}
3. Use apply to achieve a singleton mode, let's do a test. Reference the associated object C with C and C1, respectively
Package Smart.iotclass Applyclass { }class a{ def Test () =println ("function test") def apply () =println ( "Hello class A");} Object b{ def apply () =println ("Hello object B");} Similar to a factory method, use the C apply method to instantiate Aobject c{ def apply () =new A ()}object applyrun{ var c=c () println ( c.tostring) var c1=c () println (c1.tostring) }}result:[email Protected][email protected]
So what we get is actually two objects, each time C will instantiate some new a object, let's change it to a singleton mode
Package Smart.iotclass Applyclass { }class a{ def Test () =println ("function test") def apply () =println (" Hello class A ");} Object b{ def apply () =println ("Hello object B");} Similar to a factory method, use the C's apply method to instantiate Aobject c{ //Define an A object to give a default value var a:a=_ //If A is implemented, new A will return a if it has already been implemented the simple interest mode def apply () =if (a==null) {a=new a (); A}else a}object applyrun{ def main (args:array[string]): Unit = { var< C10/>c=c () println (c.tostring) var c1=c () println (c1.tostring) }}result:[email protected][ Email protected]
Scala Basics 12 Scala Application, factory method and Singleton mode implementation