Mentor SAP

Factory Methods

Restricting the visibility of the instance constructor only makes sense if somewhere within the class (or its subclasses, in case of CREATE PROTECTED) the instantiation is done.

 

Often, such classes provide a public static method that creates an instance of this class and returns the reference to this instance to the caller. Such methods are sometimes called factory methods. Factory methods are executed when an instance of the class is created and has some advantages as compared to the instance constructor.

 

Advantages of factory methods

 

Example for a Class with Factory Method

 

The example illustrates a class with a Factory Method and using a static attribute to reference all its instances. The instantiation is restricted to the class and is only done in static method FACTORY. When the method is called, the factory method checks whether an identical instance has already been created. If so, it returns the existing instance instead of creating a new one.

Hint: In this example, it is not necessary to make attributes public for the READ TABLE statement. As the factory method lies within the class, it has full access to all private attributes.

 

The Singleton Pattern

Use the singleton concept to prevent a class from being instantiated more than once for the same program context.

 

There are various different ways to implement a singleton class. The first singleton pattern is a special case of the factory concept. Instead of storing several instances, the class stores only one instance. When the factory method GET_INSTANCE is called for the first time, it instantiates the class. For every subsequent call, it returns the reference to the existing object.

 

Singleton Class - Using the Static Constructor

The class uses its static constructor to create the single instance in advance. The GET_INSTANCE method does not create the instance but only returns a reference to the already existing instance.

 

Hint: In a third variant of the singleton pattern, the GO_INSTANCE static attribute is made public and read-only. The GET_INSTANCE method is not required.