The Factory pattern 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. Here's an example of how you can implement a simple factory pattern in C#:
// Product interface
public interface IProduct
{
void Display();
}
// ConcreteProductA class
public class ConcreteProductA : IProduct
{
public void Display()
{
Console.WriteLine("This is ConcreteProductA");
}
}
// ConcreteProductB class
public class ConcreteProductB : IProduct
{
public void Display()
{
Console.WriteLine("This is ConcreteProductB");
}
}
// Factory interface
public interface IFactory
{
IProduct CreateProduct();
}
// ConcreteFactoryA class
public class ConcreteFactoryA : IFactory
{
public IProduct CreateProduct()
{
return new ConcreteProductA();
}
}
// ConcreteFactoryB class
public class ConcreteFactoryB : IFactory
{
public IProduct CreateProduct()
{
return new ConcreteProductB();
}
}
// Client class
public class Client
{
private IFactory factory;
public Client(IFactory factory)
{
this.factory = factory;
}
public void Run()
{
IProduct product = factory.CreateProduct();
product.Display();
}
}
In this example:
IProduct is the interface that declares the behavior of the products.
ConcreteProductA and ConcreteProductB are the concrete implementations of the IProduct interface.
IFactory is the interface for the factories that create products.
ConcreteFactoryA and ConcreteFactoryB are the concrete implementations of the IFactory interface, each creating a specific type of product.
The Client class uses a factory to create a product and then calls the Display method on that product.
You can use this pattern to decouple the client code from the concrete classes it creates, making it easier to extend and maintain your code. Clients can use different factories to create different products without having to worry about the details of product creation.
#AbdurRahimRatulAliKhan #ARRAK #Code #Programming #CodeDescription #Factory #DesignPatterns