Saturday, 17 May 2014

Singleton Class Creation!


1.       Create a class in SE24 which has instantiation property as private, this would create a constructor which is private.
Create Singleton Class
2.       Since constructor is private, to instantiate the class, we will need to create a Public Static method. In this public static method we will instantiate the class. To do this we will create an attribute of the type singleton class and store the reference in this attribute.
 Class Attribute 
Class Attribute
 Class Parameters
3.       Code snippet for the public static method is
Code Snipplets
  

IF gref_obj IS not BOUND.
    CREATE OBJECT gref_obj TYPE zash_singleton_test.
  ENDIF.
  ref_obj = gref_obj.

4.       Now create an attribute at instance level of type Public which will be used to store the value to be shared.
 Store Values Attribute
5.       Now create an instance of the class in Child component and set the values to beshared in WDDOINIT of a child Componentcontroller

  DATA: lo_obj TYPE REF TO zash_singleton_test.
  lo_obj ?= zash_singleton_test=>get_instance( ).
lo_obj->a_test_string  = 
'This value will be printed from calling Component '.

6.       Read this value from parent component's WDDOINIT of Componentcontroller
  DATA lo_cmp_usage TYPE REF TO if_wd_component_usage.

  lo_cmp_usage =   wd_this->wd_cpuse_z_sub_comp( ).
  IF lo_cmp_usage->has_active_component( ) IS INITIAL.
    lo_cmp_usage->create_component( ).
  ENDIF.

  DATA: lo_obj1 TYPE REF TO zash_singleton_test.
  DATA z_retrieved_value TYPE string.

  lo_obj1 ?= zash_singleton_test=>get_instance( ).
  IF lo_obj1 IS BOUND.
    z_retrieved_value = lo_obj1->a_test_string.

  ENDIF.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.