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.
UPDATE:This blog post has been updated with clear example demo on 12/17/2009. So, there could be some comments which would be obsolete.
Page Contents [hide]
What is the Singleton design pattern?
The concpet of restricting the instantiation of the a class to only and only to one object is called Singleton. As name suggests, it will restrict to create only one instance of a class. The calss will have a logic in place which will deny if the application will ask for more than one instance.
Code Lines
Let’s 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 employee’s salary account. In program, we are creating this object in a loop. So, what happens if we don’t have a design pattern which will restrict it to create more than one object. Application will create, rather overwrite an instance of the class.
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 employee’s salary account. In program, we are creating this object in a loop. So, what happens if we don’t 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
Code Snippet to check instance
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.
How to implement Singleton design Pattern in ABAP?
We can use the CLASS-DATA(static data) to save the created instance within the class and check with that instance, if application asks for a new instance.
We will look at this example.
UML diagrm for the example:
Code Snippet:
This will generate the output like this:
Update – Singleton Usage
Recently, I have posted another article on Singleton – ABAP Objects Design Patterns Singleton Usage. This article demonstrates step by step Singleton implementation along with UML sequence diagram.
SDN Wiki – Singleton design pattern
No comments:
Post a Comment