‎2008 Jun 06 8:04 AM
Hi,
How to create a Private Class & Restrict Multiple Instantiations.
Regards,
Ravi S
‎2008 Jun 06 8:57 AM
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
‎2008 Jun 07 1:29 AM
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
‎2008 Jun 10 2:11 PM
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.
‎2008 Jun 10 2:16 PM
>
> 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.