Factory Design Pattern
Factory Design Pattern is one of important design pattern which falls under Creational Design Patterns of Gang Of Four. This pattern takes responsibility of creating object. Factory Design Pattern implements loose coupling by implementing abstract entities rather than concrete implementations.
Above diagram shows a common scenario using an example of a service request factory which is able to generate two types , case creation and address changes for any account. Actual implementation for case creation and address changes is done in respective classes. ServiceRequestFactory will return object based on service type.
Implement above Scenario in Salesforce Apex:
1. Create interface IServiceRequest which have method createServiceRequest.
createServiceRequest : method is having parameter (ServiceRequestData) to get information about creating service request.
This class hold all information about case creation , address change or any other request.
Let us now implement IServiceRequest interface for specific use case. Here we are implementing for Case creation and Address Change for account. This can be used for multiple other reasons as well.
Now it is time to create factory class which will create object based on service type.
This is custom exception class to be used for logging and capturing exception information.
Now we are ready with all code. Let us see, how we can use these for creating object.
Example #1 ServiceRequestData request=new ServiceRequestData(); request.srType='Case Creation'; request.status='New'; request.description='Case Created'; IServiceRequest srRequest=new ServiceRequestFactory().getServiceRequest(request.srType); string srNo=srRequest.createServiceRequest(request); Example #2 ServiceRequestData request=new ServiceRequestData(); request.srType='Address Change Request'; request.ShippingStreet='New'; request.ShippingState='NJ'; request.ShippingCity='New Jersy'; request.ShippingCity='Somerset'; request.ShippingPostalCode='33343'; IServiceRequest srRequest=new ServiceRequestFactory().getServiceRequest(request.srType); string srNo=srRequest.createServiceRequest(request);
In example#1 we will get object of CaseServiceRequets and in second it will be object of Address Change request. ServiceRequestFactory handles object creation based on srType.
Benefits of factory pattern:
Factory pattern is most suitable pattern where some complex object creation steps are involved. Factory pattern can reduce dependency in code.