ABAP Object Design Patterns - Singleton
ABAP Object Design Patterns - Singleton
Singleton
Today we will try to explore the design patterns in the ABAP Objects. We will start with the Singleton
design pattern, which is the simplest of its family of design patterns.
Page Contents
Code Lines
Lets try to understand with an example:
We have an application which will bring the pay stub of an employee for current month. In a
standarad system, there will be only one active salary account for the employee with the
company. Because of this fact, we should only create one object of the employees salary
account. In program, we are creating this object in a loop. So, what happens if we dont
have a design pattern which will restrict it to create more than one object. Application will
create, rather overwrite an instance of the class.
In ABAP, generally we check if the instance is created or not, like:
Code Snippet to check instance
*&--------------------------------------------------------------------*
DATA: lo_application TYPE REF TO lcl_application.
IF lo_application IS BOUND.
CREATE OBJECT lo_application.
ENDIF.
But, if we take another reference to the class and create a instance of that, it will definatly
allow. So, we need to have Singleton design pattern implemented.
Code Snippet:
*&--------------------------------------------------------------------*
*& Report shows how to use the static data of the class to
*&
implement the design patterns.
*&--------------------------------------------------------------------*
REPORT ztest_singleton_pattern.
*
*---------------------------------------------------------------------*
*
CLASS lcl_application DEFINITION
*---------------------------------------------------------------------*
CLASS lcl_application DEFINITION CREATE PRIVATE.
*
PUBLIC SECTION.
*
Static Method which will return us the object reference
CLASS-METHODS:
get_apps_instance
RETURNING
set_v_name
IMPORTING
*
*
*
PRIVATE SECTION.
static class reference to hold the existing object reference
CLASS-DATA: lo_apps TYPE REF TO lcl_application.