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: 

Restricting Multiple Instances

Former Member
0 Kudos

Hi,

How to create a Private Class & Restrict Multiple Instantiations.

Regards,

Ravi S

4 REPLIES 4

uwe_schieferstein
Active Contributor
0 Kudos

Hello Ravi

I assume you are talking about the SINGLETON pattern.

Define the instantiation of your class as private.

Define a static private attribute MO_INSTANCE of TYPE REF TO <name of your class>.

To instantiate you need a static method (e.g. CREATE) which return an instance of your class (e.g. RETURNING parameter RO_INSTANCE).

METHOD create.

  IF ( mo_instance IS BOUND ).
    ro_instance = mo_instance.
  ELSE.
    CREATE OBJECT mo_instance. 
    ro_instance = mo_instance.    
  ENDIF.
    

ENDMETHOD.

Regards

Uwe

0 Kudos

Hi Ravi,

in addition to Uwe's advice you should define the class with "PRIVATE" instantiation. This has the effect of making it impossible to instantiate the class from outside itself - so only Uwe's CREATE method can be used to instantiate it.

There is a good SAP Press publication that covers this. It is called "Design Patterns in Object-Oriented ABAP" by Igor Barbaric.

Cheers

Graham Robbo

Former Member
0 Kudos

Hi Ravi,

Through SE24 T-code we can handle the access specifiers(Public,Private,Protected) of a class.

While creating a class with SE24,the second screen's Instantiation field contains - 'Public,Private'..here we can declare Private to make the class private.This is the best way to handle the visibility of a class.

And among the checkboxes 'Final & Only Modeled' ,only Final must be checked for this class to have no more instances.

Do reward me if you find helpful.

matt
Active Contributor
0 Kudos

>

> And among the checkboxes 'Final & Only Modeled' ,only Final must be checked for this class to have no more instances.

>

> Do reward me if you find helpful.

This is not correct. Final prevents subclassing. It has no effect whatsoever on instantiation.