In C#, the Factory Method is a creational design pattern that provides an interface for creating instances of a class, but allows subclasses to alter the type of instances that will be created. It falls under the Gang of Four (GoF) design patterns and is categorized as a creational pattern because it deals with object creation mechanisms.
Here's how the Factory Method pattern typically works:
1. Creator Class: This is an abstract or concrete class that declares the factory method. The factory method is typically an abstract method in an abstract class, allowing subclasses to implement this method to create instances of a specific type.
2. Concrete Creator Classes: These are subclasses that extend the creator class and implement the factory method to create instances of a specific type.
3. Product Class: This is the class or interface that represents the product created by the factory method.
The key idea behind the Factory Method pattern is to defer the instantiation of an object to its subclasses, allowing the subclasses to determine the class type of the objects that will be created.
Here's a simple example in C#:
// Product interface or class
interface IProduct
{
void Display();
}
// Concrete product
class ConcreteProduct : IProduct
{
public void Display()
{
Console.WriteLine("Concrete product");
}
}
// Creator abstract class with the factory method
abstract class Creator
{
public abstract IProduct FactoryMethod();
}
// Concrete creator
class ConcreteCreator : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProduct();
}
}
class Program
{
static void Main(string[] args)
{
// Create a concrete creator
Creator creator = new ConcreteCreator();
// Use the factory method to create a product
IProduct product = creator.FactoryMethod();
// Display the product
product.Display();
}
}
In this example, ConcreteCreator implements the factory method to create an instance of ConcreteProduct. The Main method demonstrates how to use the factory method to create a product.
No comments:
Post a Comment