The Singleton object Markerfactory in the previous section is an example of a standalone object. Although it manages the marker class, it is not associated with any class.
Scala can also create objects that are associated to a class. Such objects share the same name, and such objects are called associated objects, and the corresponding classes are called companion classes. In Scala, classes and associated objects have no bounds, and they can access each other's private methods and private properties. The following uses the associated object to rewrite the marker:
classMarkerPrivate(Val color:string) {println ("Creating" + This) override Def toString (): String= "Marker Color" +color}object Marker {PrivateVal markers = Map ("Red"NewMarker ("Red"), "Blue"NewMarker ("Blue"), "Green"NewMarker ("Green")) def getmarker (color:string)=if(Markers.contains (color)) markers (color)Else NULL}
In the reconstructed code, a new companion object is created for the marker class, and the associated object is an instance of the Marker class. It also uses private to modify the main constructor of the marker, ensuring that only its associated objects can create instances of the marker class, thus guaranteeing the singleton characteristics of the marker class. Of course, it is also possible not to declare the main constructor of the marker class as private, but at this point the Marker object as a singleton implementation of the Marker class is still not strict.
Call the Marker class using the following code:
println (Marker getmarker "Blue" "Blue" "Red" "Red")
The output is as follows:
Each class can have associated objects. Associated objects and associated classes are written in the same file, and the associated objects are common in Scala, and they provide a convenient way to operate at the class level. In some ways, they can also act as a workaround for Scala's lack of static members.
######
Scala Learning Notes 15-independent objects and associated objects