What are the Strategy and Factory design patterns in Apex?
Suggested answer
Strategy Pattern: Define a family of algorithms behind a common interface. A context class delegates to the appropriate strategy at runtime. Example: different discount calculation strategies (percentage, fixed amount, tiered) all implement a IDiscountStrategy interface with a calculate(Decimal price) method. The caller passes the strategy it wants. In Apex, commonly used in email dispatch logic, notification strategies, or complex calculation variations. Factory Pattern: A factory class creates instances of classes without the caller needing to know the concrete type. Example: TriggerHandlerFactory.getHandler('Account') returns the AccountTriggerHandler. In enterprise patterns (fflib), the Application class acts as the factory for Selectors, Domains, and Services. Factories enable dependency injection and allow tests to swap in mock implementations.
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.