Singleton Pattern in ABAP
Apr 15, 2012
Object Oriented Programming has been a boon to the programmers without which development of huge systems is almost impossible. ABAP is no exception to that which is why Object Oriented Programming was added to ABAP.
Without the use of Design Patterns, Object Oriented Programming is never going to give fruitful results. There are so many patterns that are proposed and being proposed. If you are not learning simple and common the Design Patterns, one day you will hit the dead end or you will spend time reinventing the wheel. To have a good knowledge in Design Patterns, I would suggest you to go with the Design Patterns: Elements of Reusable Object-Oriented Software by Gang of four. Here I would like to give an implementation of one such very common pattern.
Sometimes, we want only one instance of an object to be present in the entire lifetime of the system. A security or authentication system, logging system or a database connection should not be having more the one instance. In such cases, the Singleton Pattern comes to the rescue. Singleton Pattern does not mean to produce a single instance always; it can produce n number of instances where the n is constant.
Now I would like to share you an example of Singleton Pattern implemented in ABAP. Here a counter is made as a singleton object so that the counter can be incremented from anywhere and also making sure that only one counter exists.
A class which implements Singleton Pattern should have the following things other than the class’s own data members and methods,
- Private constructor(s)
- A private static member of the same type of the class.
- A static method which returns the only instance.
counter
class’s definition and implementation is as follows,
REPORT ZFAR_SINGLETON.
class counter definition create private. "Rule 1
public section.
class-methods:
get_counter returning value(obj) type ref to counter. "Rule 3
methods:
increment,
get_count returning value(cnt) type i.
private section.
class-data instance type ref to counter. "Rule 2
data count type i.
endclass.
class counter implementation.
method get_counter.
if instance is initial.
create object instance.
endif.
obj = instance.
endmethod.
method increment.
add 1 to count.
endmethod.
method get_count.
cnt = count.
endmethod.
endclass.
start-of-selection.
data: ctr1 type ref to counter,
ctr2 type ref to counter,
num1 type i,
num2 type i.
ctr1 = counter=>get_counter( ).
ctr1->increment( ).
ctr2 = counter=>get_counter( ).
ctr2->increment( ).
num1 = ctr1->get_count( ).
num2 = ctr2->get_count( ).
write: num1, num2.
Since there is only one instance exists, both the references point to the same object and operates on the same object. Use Singleton Pattern whenever possible to ensure good design of the system.