Skip to Content
Author's profile photo Former Member

Singleton Pattern in ABAP

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 some 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 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,

            1. Private constructor(s)

            2. A private static member of the same type of the class.

            3. 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.

– Fareez Ahamed K.N.

Assigned Tags

      17 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Dirk Wittenberg
      Dirk Wittenberg

      Hi Fareez,

      great blog. I appreciate much your mentioning the book of the gang of four. It's a must read also for ABAP-devs.

      Regarding the Singleton-Pattern: I always try to do TDD and from this point of view this pattern entails some issues. Within unit tests every test should run with its own instance of the class under test. And this is simply not possible with a singleton.

      Michael Feathers mentions 2 workarounds in his book "Effectively working with legacy code":

      1.

      Insert a method destroy:

      method destroy.

      clear instance.

      endmethod.

      2.

      Insert a method "testsetter"

      methods testsetter importing i_instance type ref to counter.

      method testsetter.

      instance = i_instance.

      endmethod.

      To make sure, that theses methods are only used within tests you can make them private and declare the test-class as friend so that it is allowed to call the private methods.

      So it's a long comment. I hope it complements your blog.

      Regards,

      Dirk

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      Hi Dirk,

      I would like to thank you so much for spending your time on giving a valid comment. I tried to a very simple implementation here for beginners who are not aware of singleton pattern so I restricted myself from making it complex. I completely adhere with your idea.

      Regards,

      Fareez

      Author's profile photo Adam Krawczyk
      Adam Krawczyk

      Hi Dirk and Fareez,

      Nice blog and comments.

      I just want to add three comments:

      1. Such implemented singleton works only within internal session.

      Default singleton implemementation does not work as in case of Java language, where once initialized singleton stays until end of program runtime.

      If you run program from another transaction while first is running, or if you submit other report inside program and use get_instance in main and submitted program, new get_counter( ) method will create new object in each.

      Class must be marked as shared memory enabled, then it will be session independent singleton. This is useful in case of global classes, your example shows local class usage, so it is enough.

      2. I would not recommend to add method with name "testsetter".

      I agree with the logic which I use often but I do not like such name of the method. Generally we should avoid extending production code with test method that helps with testing. Logic of testing should be split from production used code. That is why I do not like method name "testsetter". Instead, I would just make public method set_instance or set_counter as for code above. Such method does not suggest by name that is is test method only. Actually it maybe also used in production code if instance of singleton must be replaced/injected during runtime.

      3. For singleton pattern I would use common naming convention get_instance( ) or get_singleton_instance( ) in general as this quickly informs by name that it is singleton. But it may be also developer's preference.

      Regards,

      Adam

      Author's profile photo Dirk Wittenberg
      Dirk Wittenberg

      Hi Adam,

      you're right, the name "testsetter" is not the best choice. I just wanted to point out what for it is used.

      Regards,

      Dirk

      Author's profile photo Trond Stroemme
      Trond Stroemme

      So, just to clarify: a singleton which is not shared memory-enabled would exist locally within the user's session, right? Because my perception of singletons (as used to transfer attributes between separate WDA components, for example) is that any user executing the same functionality on the same system will have their own singletons created - the "one instantiation only" is only valid within the user session context. Am I correct?

      Regards,

      Trond

      Author's profile photo Dirk Wittenberg
      Dirk Wittenberg

      Hi Trond,

      yes every user has its own instantiation. Unless you're implementing the singleton as shared object.

      Regards,

      Dirk

      Author's profile photo Custodio de Oliveira
      Custodio de Oliveira

      Hi Fareez,

      Nice and simple example of singleton. I suggest you all read Chris Paine 's blog (AND comments): Sorry Singleton I don't love you anymore.

      Cheers,

      Custodio

      PS: I do use singleton sometimes 😉

      Author's profile photo Former Member
      Former Member

      Nice blog...

      Author's profile photo Raju C D
      Raju C D

      Good one, thanks for sharing with good example...

      Author's profile photo Raju C D
      Raju C D

      Very Good Blog, useful content..

      Author's profile photo Timo John
      Timo John

      Hi

      for more patterns check:

      OO Design Patterns | ABAP Help Blog 

      😎

      thanks to Naimesh Patel for his nice site outside the SCN.

      Author's profile photo Former Member
      Former Member

      In real time where we use singleton class?

      please don't give any condition or code. I just need the situation where we can use it.

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      Hi Masoom,

      There are lot of applications for Singleton class. Say you are having a DatabaseConnection class. At any point of time you need only one instance of DatabaseConnection exist throughout the application so that all queries that you pass to the database pass through a same object.

      There are a variety of situation. I'll suggest you to look into a good Design pattern book for better understanding of the Singleton or any other pattern.

      Wasalam

      Fareez Ahamed

      Author's profile photo Former Member
      Former Member

      Hi Fareez/Masson

      I would use a static class for Database connection than a singleton. Singleton can be used when you need only one instance of a specific object but you may have many implementations of the class.

      As of the above example you have a counter class, and you need to only one instance of the carCounter and one instance of the busCounter.

      Personally I like using the singleton with factory pattern together.

      Thanks

      Author's profile photo Adam Krawczyk
      Adam Krawczyk

      Hi Christos,

      Personally I prefer to use singleton for database access and use DAO pattern (Data Access Object). If you have static method in the class you cannot override it. If you use your singleton object inside business logic (production code) there is a way to use dependency injection so that you replace real DAO object with the fake one in the runtime and this is the gate for unit testing without database access. I refer to my blog about DAO concept if you are interested in the topic 🙂

      Regards,

      Adam

      Author's profile photo Former Member
      Former Member

      Nice blog. Thank you.

      Author's profile photo Former Member
      Former Member

      simple and nice explanation with an example.

      jazakallah khair.