What is the Singleton pattern in Apex and where is it used?
Suggested answer
The Singleton pattern ensures a class has only one instance per transaction. In Apex, this is implemented using a static variable: private static MyClass instance; public static MyClass getInstance() { if (instance == null) instance = new MyClass(); return instance; }. Common uses:
1. Configuration caches: Load Custom Metadata or Custom Settings once and cache in the singleton instance to avoid repeated SOQL queries across multiple trigger invocations in the same transaction.
2. Trigger context flags: The recursion-prevention flag is effectively a singleton state.
3. Service locators: The Application Factory in enterprise patterns uses singletons. Important: in Apex, static variables are reset per transaction — the singleton lives only within one transaction context.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.