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

我怕爱的太早我们不能终老 提交于 2019-12-21 04:35:06

问题


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.


回答1:


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();
    }
}



回答2:


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() { ... }

I hope it helps, Carlos.



来源:https://stackoverflow.com/questions/2194629/ddd-book-eric-evans-what-is-meant-by-the-factory-should-be-abstracted-to-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!