11-23-2020 12:24 PM
Hi,
Please explain the Singleton design pattern with an example.
If you know any requirement you worked on please explain.
Regards,
Manjunath M
11-23-2020 12:26 PM
Hello manjunathm
http://zevolving.com/2008/09/abap-object-design-patterns-singleton/
Kind regards,
Mateusz
11-23-2020 12:26 PM
Hello manjunathm
http://zevolving.com/2008/09/abap-object-design-patterns-singleton/
Kind regards,
Mateusz
11-23-2020 3:17 PM
Singleton pattern restricts multiple instantiation of a class by just letting create one instance.
The following is a short example of the singleton pattern.
report zsingleton.
class cl_singleton definition.
public section.
class-data p_my_class type ref to cl_singleton.
class-methods get_instance returning value(r_my_class) type ref to cl_singleton.
endclass.
class cl_singleton implementation.
method get_instance.
if p_my_class is initial.
write / 'Created new instance'.
p_my_class = new #( ).
else.
write / 'Do not create new instance. Just return the same created before'.
endif.
r_my_class = p_my_class.
endmethod.
endclass.
data lcl_my_class type ref to cl_singleton.
start-of-selection.
lcl_my_class = cl_singleton=>get_instance( ). " -> Output: Created new instance
lcl_my_class = cl_singleton=>get_instance( ). " -> Output: Do not create new instance. Just return the same created before
lcl_my_class = cl_singleton=>get_instance( ). " -> Output: Do not create new instance. Just return the same created before
break-point.
For more information visit this link: https://en.wikipedia.org/wiki/Singleton_pattern.
11-25-2020 3:32 AM
Hi manjunathm
* Singleton means Private instantiation and globally access.
* Singleton class object create with in the class only we cant create a object outside the class but we can access the components of that singleton class.
* Creating a class in such way so that we can create exactly one object is called as singleton.
REPORT ZAK_SINGLETON.
class ZCL_SINGLETON_LOGIN definition
final
create private .
public section.
class-methods LOGIN.
private section.
class-data LV_INST type ref to ZCL_SINGLETON_LOGIN .
class-methods INSTANCE
returning
value(RO_INST) type ref to ZCL_SINGLETON_LOGIN .
ENDCLASS.
CLASS ZCL_SINGLETON_LOGIN IMPLEMENTATION.
method INSTANCE.
IF LV_INST IS NOT BOUND.
CREATE OBJECT RO_INST.
LV_INST = RO_INST.
ELSE.
RO_INST = LV_INST.
ENDIF.
endmethod.
method LOGIN.
write : 'Demo For Singleton'.
endmethod.
ENDCLASS.
START-OF-SELECTION.
ZCL_SINGLETON_LOGIN=>LOGIN( ).
Thankyou.
11-25-2020 2:54 PM
WIth SingleTon, I think the most important is to show that, two separated report access the same instance :
https://answers.sap.com/questions/12988109/how-do-we-use-singleton-in-oo-abap-can-someone-ple.html