Fully aware that this is another question from the series "The Difference Between an Abstract Class and an Interface." And I have to say that for me these two concepts are clear or maybe no time I ask this question :)
Probably every second, if not the first of the developers uses the generating pattern "Factory Method" and I am interested in the question, so what abstraction is better to use when implementing this pattern: an абстрактный класс or интерфейс ?
The tutorials in the network are also not united in this: someone tells this pattern with the help of an abstract class, and someone with the help of interfaces. Although I should note that most of the articles regarding the factory method are based on abstract classes.
Here is an example from Wikipedia, which tells the pattern on
Abstract classes
namespace CSharpConsoleApp { abstract class AbstractProduct { public abstract string GetType(); } class ConcreteProductA : AbstractProduct { public override string GetType() { return "ConcreteProductA"; } } class ConcreteProductB : AbstractProduct { public override string GetType() { return "ConcreteProductB"; } } abstract class AbstractCreator { public abstract AbstractProduct FactoryMethod(); } class ConcreteCreatorA : AbstractCreator { public override AbstractProduct FactoryMethod() { return new ConcreteProductA(); } } class ConcreteCreatorB : AbstractCreator { public override AbstractProduct FactoryMethod() { return new ConcreteProductB(); } } class Program { static void Main(string[] args) { AbstractCreator[] creators = { new ConcreteCreatorA(), new ConcreteCreatorB() }; foreach (AbstractCreator creator in creators) { AbstractProduct product = creator.FactoryMethod(); Console.WriteLine("Created {0}", product.GetType()); } Console.Read(); } } } And this is a version I converted to
Interfaces
namespace CSharpConsoleApp { interface IProduct { string GetType(); } class ProductA : IProduct { public string GetType() { return "ProductA"; } } class ProductB : IProduct { public string GetType() { return "ProductB"; } } interface ICreatorProduct { IProduct FactoryMethod(); } class CreatorProductA : ICreatorProduct { public IProduct FactoryMethod() { return new ProductA(); } } class CreatorProductB : ICreatorProduct { public IProduct FactoryMethod() { return new ProductB(); } } class Program { static void Main(string[] args) { ICreatorProduct[] productCreators = { new CreatorProductA(), new CreatorProductB() }; foreach (ICreatorProduct creatorProduct in productCreators) { IProduct product = creatorProduct.FactoryMethod(); Console.WriteLine("Created {0}", product.GetType()); } Console.Read(); } } } So what is the best practice for using this pattern in terms of abstractions?