09-22-2008 4:57 PM
Hi All,
How can I restrict a class to have only one reference or object.
I have created a class and now I am creating objects(references) for this class.
Now I shouldnt be able to create more than one object to this class.
Please clarify my doubt.
Thanks,
Prasad
09-22-2008 5:17 PM
09-22-2008 5:34 PM
if you have created an instance of a class, you can check this variable to be initial or not...
09-22-2008 6:44 PM
In my opinion he wants to allow one instance over all reports/modules.
09-22-2008 9:03 PM
Hello Prasad
You are looking for the singleton design pattern. Have a look at sample report ZUS_SDN_ABAP_OO_SINGLETON.
*&---------------------------------------------------------------------*
*& Report ZUS_SDN_ABAP_OO_SINGLETON
*&
*&---------------------------------------------------------------------*
*& Thread: Objects to a class
*& <a class="jive_macro jive_macro_thread" href="" __jive_macro_name="thread" modifiedtitle="true" __default_attr="1056939"></a>
*&---------------------------------------------------------------------*
REPORT zus_sdn_abap_oo_singleton.
*----------------------------------------------------------------------*
* CLASS zcl_myclass DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS zcl_myclass DEFINITION CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS:
create
RETURNING value(ro_instance) TYPE REF TO zcl_myclass.
METHODS:
constructor. " NOTE: instantiation is private !!!
PRIVATE SECTION.
CLASS-DATA:
mo_instance TYPE REF TO zcl_myclass.
ENDCLASS. "zcl_myclass DEFINITION
*----------------------------------------------------------------------*
* CLASS zcl_myclass IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS zcl_myclass IMPLEMENTATION.
" Creating instance only via static factory method possible!
METHOD create.
IF ( mo_instance IS BOUND ).
ro_instance = mo_instance.
ELSE.
CREATE OBJECT ro_instance.
ENDIF.
ENDMETHOD. "create
METHOD constructor.
mo_instance = me.
ENDMETHOD. "constructor
ENDCLASS. "zcl_myclass IMPLEMENTATION
data: go_instance_1 type ref to zcl_myclass,
go_instance_2 type ref to zcl_myclass.
START-OF-SELECTION.
BREAK-POINT.
go_instance_1 = zcl_myclass=>create( ).
go_instance_2 = zcl_myclass=>create( ).
BREAK-POINT.
END-OF-SELECTION.
Regards
Uwe
09-23-2008 4:47 AM
Hi Prasad,
This is a common design problem. The solution to this is Singleton Pattern. In this design pattern we design our class in such a way that only one instance can be created.
Read the tutorial on [ABAP Singleton Classes|http://www.abaplearning.com/abap-tutorials/abap-objects/8-abap-objects/35-singleton-classes].
This tutorial describes the concept of singleton and how to achieve it in ABAP Objects.
Cheers.
Varun