What is the Factory
Method Design Pattern?
As per Factory Method
Design Pattern is used when we want to create the object of the class without
exposing the logic of object creation to the client.
According to the Gang
of Four Definition “Define an interface for creating an object, but let
the subclasses decide which class to instantiate. The Factory method class
defer instantiation it uses to subclasses”.
to implement it in the
factory method design pattern we need to create the abstract class as part of
the Factory class which will create an object and return the object of the
product class, and here subclasses will decide which class needs to instantiate.
The Factory Method
Design Pattern is a creational pattern that provides an interface for creating
objects in a superclass but allows subclasses to alter the type of objects
that will be created. This pattern helps in defining a method that will create
objects, and it lets the subclasses decide which class to instantiate.
Here is a real-time
example in C#: creating a logging framework where different types of loggers
(e.g., Console Logger, File Logger) can be instantiated based on the
configuration.
Step 1: Define the Product Interface
Step 5: Use the Factory Method Pattern
Explanation
- ILogger: The product interface that defines the Log method.
- ConsoleLogger and FileLogger: Concrete product
classes that implement the ILogger interface.
- LoggerFactory: The abstract creator class that defines
the factory method CreateLogger. It also provides a LogMessage method that
uses the logger created by the factory method.
- ConsoleLoggerFactory and FileLoggerFactory: Concrete
creator classes that implement the factory method to create instances of ConsoleLogger
and FileLogger, respectively.
- Program: The client code that uses the factory method pattern to log
messages using different types of loggers.
Summary
The Factory Method
Design Pattern:
- Defines an interface for creating an
object, but lets subclasses alter the type of object that will be created.
- Helps in decoupling the client code from
the concrete classes it needs to instantiate.
- Provides flexibility to introduce new
types of loggers without modifying the client code.
In this example, the
logging framework can be extended to support more types of loggers (e.g.,
Database Logger, Network Logger) by simply adding new concrete creator classes
without changing the existing client code.
1 comments:
Write commentsNice and simple way to understand the Factory method design pattern . Thanks
EmoticonEmoticon