Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Singleton design pattern in OO ABAP

0 Kudos

Hi,

Please explain the Singleton design pattern with an example.

If you know any requirement you worked on please explain.

Regards,

Manjunath M

1 ACCEPTED SOLUTION

mateuszadamus
Active Contributor
4 REPLIES 4

mateuszadamus
Active Contributor

nmirandaghn
Participant

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.

0 Kudos

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.

FredericGirod
Active Contributor

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