This article describes how to implement a Singleton design pattern in Apex. The Singleton pattern attempts to solve the issue where you are repeatedly using an object instance but only wish to instantiate it once within a single transaction context. Common uses for this pattern include:
However, it's most common use is to create an object instance that's instantiated only once for the lifetime of that execution context.
For the parent page to this article, and for a full list of other design patterns, go to Apex Design Patterns.
Often developers can write inefficient code that can cause repeated instantiation of objects. This can result in inefficient, poorly performing code, and potentially the breaching of governor limits. This most commonly occurs in triggers, as they can operate against a set of records.
The following code shows an example of repeated code invocation that can result in a breach of governor limits:
The trigger will cause a repeated execution of the sObject getDescribe() method, resulting in a breach of the total number of describes governor limit if the trigger operates against more than 100 records.
In order to implement a Singleton pattern in Apex, the class must instantiate only a single instance and be globally accessible. It is implemented by:
The following code sample demonstrates an implementation of the Singleton pattern to return a record type describe within a trigger:
The Singleton Class
The above code demonstrates the following:
This allows the trigger to obtain a reference to the record type without breaching governor limits.
The following code sample shows how to use eager-initialization so that a new instance is always created when the class is instantiated.
The Singleton Class - Eager Initialization variant
The instance of the class is instantiated as a final, static variable, which means that only one instance ever exists. This method is typically used if the cost of creating the instance is small.
The Singleton design pattern allows Apex code to repeatedly reference an object instance in an optimal manner, whilst mitigating the impact of governor limits.
See the Apex Design Patterns article for more design patterns.