top of page

Factory Design Pattern in Apex

Introduction


The Factory Design Pattern is a widely used creational design pattern that allows you to create objects without exposing the object creation logic to the client. It provides a way to centralize object creation logic in a single factory class. In this blog post, we will discuss the Factory Design Pattern in the context of Apex development and provide a sample code implementation.


Factory Design Pattern


The Factory Design Pattern is a creational pattern that defines an interface for creating an object but let's subclasses decide which class to instantiate. The Factory Method lets a class defer instantiation to subclasses.


The Factory Design Pattern consists of the following components:

  1. Creator: This is an abstract class or interface that defines a factory method. The factory method returns an object of the Product type.

  2. ConcreteCreator: This is a class that implements the factory method and returns an object of the Product type.

  3. Product: This is an abstract class or interface that defines the interface for the objects that the factory method creates.

  4. ConcreteProduct: This is a class that implements the Product interface.

Example Code:


In this example, we will create a factory that will produce different types of shapes. The factory will have a single method that will take a shape type as a parameter and return an instance of that shape.


We will start by creating the Product interface, which will define the interface for the objects that the factory method creates.


Next, we will create the ConcreteProduct classes that implement the Shape interface.


Now, we will create the Creator interface, which will define the factory method that creates the products.


Next, we will create the ConcreteCreator class that implements the ShapeFactory interface.


Finally, we can use the factory to create different types of shapes.


Output:


Conclusion:


The Factory Design Pattern is a useful pattern that allows you to create objects without exposing the object creation logic to the client. It provides a way to centralize object creation logic in a single factory class. In this blog post, we discussed the Factory Design Pattern in the context of Apex development and provided a sample code implementation. By using the Factory Design Pattern, you can create code that is more modular, maintainable, and extensible.

Recent Posts

See All

1 則留言


Sridhar NareshIT
Sridhar NareshIT
2023年7月28日

Thanks for sharing useful information on Apex, Very easy to understand keep posting more information.


按讚
bottom of page