using System;
namespace FactoryMethodPattern
{
// Concrete Product A
public class ConcreteProductA : IProduct
{
public void Use()
{
Console.WriteLine("Using ConcreteProductA");
}
}
}
ConcreteProductB.cs
using System;
namespace FactoryMethodPattern
{
// Concrete Product B
public class ConcreteProductB : IProduct
{
public void Use()
{
Console.WriteLine("Using ConcreteProductB");
}
}
}
3. Creator.cs (Abstract Factory Class)
namespace FactoryMethodPattern
{
// Abstract Creator
public abstract class Creator
{
// Factory Method: Must be implemented by concrete creators
public abstract IProduct FactoryMethod();
}
}
namespace FactoryMethodPattern
{
// Concrete Creator A
public class ConcreteCreatorA : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProductA();
}
}
}
ConcreteCreatorB.cs
namespace FactoryMethodPattern
{
// Concrete Creator B
public class ConcreteCreatorB : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProductB();
}
}
}
5. Program.cs (Client Code)
using System;
namespace FactoryMethodPattern
{
class Program
{
static void Main(string[] args)
{
// Create a factory for ProductA
Creator creatorA = new ConcreteCreatorA();
IProduct productA = creatorA.FactoryMethod();
productA.Use(); // Output: Using ConcreteProductA
// Create a factory for ProductB
Creator creatorB = new ConcreteCreatorB();
IProduct productB = creatorB.FactoryMethod();
productB.Use(); // Output: Using ConcreteProductB
}
}
}
🎯 Key Takeaways
✅ Encapsulation: The client does not know which concrete product it gets.
✅ Scalability: Easily add new products and factories.
✅ Decoupling: The factory method isolates the creation logic.
No comments:
Post a Comment