Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DDD Book, Eric Evans: What is meant by "The FACTORY should be abstracted to the type desired rather than the concrete class(es) created."?

In the book Domain Driven Design, by Eric Evans, in Chapter 6 in the section on "Factories" (page 139) it says the following:

"The two basic requirements for any good FACTORY are:

...

"2. The FACTORY should be abstracted to the type desired rather than the concrete class(es) created."

Could you please elaborate on what is meant by that statement about basic requirement number 2.

like image 993
JW. Avatar asked Feb 03 '10 19:02

JW.


2 Answers

I think it means you should never return a concrete type from your factory.

For example, if you have an interface, let's say ISomething, an abstract class SomethingBase and finally some classes that implement this interface and inherit from the base class. Your creation method should return the interface type, instead of the base type. I think that is the idea.

public ISomething Create() { ... }

Instead of

public SomethingBase Create() { ... }
like image 170
CARLOS LOTH Avatar answered Nov 06 '22 13:11

CARLOS LOTH


Carlos Loth's answer is correct, but you should always remember to use an Abstract Factory as well, as this will allow you to couple concrete factories to concrete types without coupling consumers to concrete factories or types.

public interface ISomethingFactory
{
    ISomething Create();
}

public class SomethingFactory : ISomethingFactory
{
    public ISomething Create()
    {
        return new Something();
    }
}
like image 8
Mark Seemann Avatar answered Nov 06 '22 13:11

Mark Seemann