This post is part of the series – Design Pattern in Apex
Singleton Design Pattern is pretty popular and one of the simplest design pattern available.
- Ensure that only one instance of class is getting created.
- Provide a global point of access to the object.
There are many ways to implement Singleton Pattern in apex. Let’s start with few case scenarios:
Whenever a new account is getting inserted to Salesforce, it should be synced with MDM(Master Data Management) through integration. But if MDM system is down, then Salesforce should not got for synchronization.
Let’s start implementing the requirement –
Custom Settings – Integration – This will be used to identify whether MDM System is up and running. If MDM System is down, Admin will uncheck the value and then Salesforce will not try for synchronization. Below is how custom settings will look like –
Now if you test, this code will work fine. But this code is having a very basic problem.
Let’s understand the problem first by going through the trigger. Consider line#2 where we are iterating through the list of accounts via Trigger.new. Now think of a scenario where we are inserting huge amount of accounts through dataloader. So in that case Trigger.new will return us huge list and we will iterate through each account and create an instance of our AccountHelper class.
Now inside AccountHelper class constructor, we are checking values from our custom settings.
So what will happen, for all the records, we will create a new instance and query custom object every time. Do you think this is really necessary?
Definitely not. But why? The reason is that in the same transaction, we don’t need to create multiple instances and check custom settings every time. In a single transaction, if Trigger.new is returning us a list of 200 accounts, we should create a single instance of AccountHelper class which will query our custom objects once. Great!! But now the question is how we can achieve that ??
Below is the updated code –
Below are the changes –
- The static getAccountHelperInstance() method will only instantiate an instance of the class if it doesn’t already exists.
- The constructor and accountHelperInstance variable is private, which will make sure that it cannot be instantiated outside of the getAccountHelperInstance() method.
I hope this will help you to understand why we need Singleton Design Pattern. I will write few more use cases in my next posts. Till then if you have any feedback, please let me know.
Wishing you a happy learning.