Factory Method Design Pattern in Apex | Pure Polymorphism in Salesforce

by - 4:18 PM

When do we need this ? 

We need the factory pattern design whenever we deal with problem of creating objects without specifying the class of object. In other words, dynamic classes execution , so basically we define an interface to create an object and let the classes implementing this interface decide which class needs to instantiate (create an  object)

You can read more about 'factory pattern' here' and 'here'

Basic Implementation in my favorite platform .net is shown below (credit:wikipedia)

How to Implement Factory Pattern in Apex ?

In here, I designed a factory class that defines an interface (implemented by all the classes),  the manager will instantiate each product class and call the method (custom defined by each class).

Here is the manager class - the instantiate a class

The manager class object will instantiated here in the bulkprocess() method, which in turn create the instance of each class.

I believe this clearly defines how to implement Factory Pattern in Apex. Another interested articles is written by Alex Berg on designing unit test based using factory pattern in Apex

- Unit Test using factory method in Apex 

You May Also Like