How to use Factory Method Pattern in C#
By FoxLearn 2/16/2024 3:21:40 PM 329
Factory Method pattern is used to define an interface that creates an object, but only for the subclass to decide which class is used to create the object according to that class.
It can be used to create the first interface class and specify the following concrete class.
Regular usage: Very high
UML Diagram
lasses and objects that participate in this pattern include:
- Product: defines the interface of the object that the factory method creates.
- ConcreteProduct: implements Product interface classes.
- Creator: Defining a factory method, returning one object is a specific type of product. Creator can be the default factory method that returns the default ConcreteProduct object, it can call the factory method to create the Product object.Defining a factory method
- ConcreteCreator override factory method to return the ConcreteProduct instance.
Implement C# code
class BuilderPattern { static void Main() { Creator[] creators = new Creator[2]; creators[0] = new ConcreteCreatorA(); creators[1] = new ConcreteCreatorB(); foreach (Creator creator in creators) { Product product = creator.FactoryMethod(); Console.WriteLine("Created {0}", product.GetType().Name); } } } abstract class Product { } class ConcreteProductA : Product { } class ConcreteProductB : Product { } abstract class Creator { public abstract Product FactoryMethod(); } class ConcreteCreatorA : Creator { public override Product FactoryMethod() { return new ConcreteProductA(); } } class ConcreteCreatorB : Creator { public override Product FactoryMethod() { return new ConcreteProductB(); } }
Result
Created ConcreteProductA Created ConcreteProductB