|
Often, there is a requirement that you would want to create only one instance of the class. To put it in other words, you do not want any one to create instance of the class if already created. This is a common requirement in many application designs. So how do we achieve this ? This can be achieved using the singleton pattern. In this design pattern, we will declare the constructor as a 'Private' one. Private constructor !! Is that possible?
Yes, it is. Go to the properties tab of class builder (SE24) and change the instantiation type to private. Then you can create a private constructor. The advantage of having a private constructor is that now no one can create an object of your class.. not even you  So how do we create the instance of this class ? We create a static method GET_INSTANCE that will be used to create the instance. A static method because this method can be called directly with the class reference (without an object). Inside this method, we can create the object (because the constructor is a private method, we can call it within class). Now, how to make sure that only one instance is created? Simple. Store the own reference as an attribute of the class. In the method GET_INSTANCE check if this attribute is populated. If it populated then return the same instance. If not, create a new one, store it in the own attribute and return the instance. An example implementation of GET_INSTANCE is shown here. Lets say the name of the attribute is GREF_OBJ. IF gref_obj IS INITIAL. CREATE OBJECT gref_obj TYPE (class name).
ENDIF. RETURN gref_obj. An example how to create the instance of the class is shown here: lref_obj = (class_name)=>get_instance_of().
|