This post is part of the series – Design Pattern in Apex
Today in this post I will explain how Singleton Design Pattern can
be used to call global describe only once.
When someone inserts an account record, you need to inspect all the fields in the account object.
Below is the trigger to start with –
The problem with this approach is that when someone enters huge number of accounts with dataloader, this code will work like –
For each insert, it will create a new instance of AccountHelper which in turn will execute GlobalDescribe(). Very soon we will be hit by LimitException.
To avoid that, we have to implement Singleton Design Pattern and below are the changes we need to do that –
Now you can see for a single transaction, we are calling GlobalDescribe only once because we are now not instantiating AccountHelper object for each Account insert, rather we are only instantiating one AccountHelper object per transaction.
Hope you understood the usages of Singleton Design Pattern. If you have implemented this design pattern in any other situation, requesting you to share here. Thanks for your feedback. Thanks.
- Google Cloud
- Web Technology