Abstract Factory vs Factory method: Composition vs Inplement? [duplicate]

喜欢而已 提交于 2019-12-08 08:24:51

问题


I have read a lot of posts about different between Abstract Factory and Factory method, but there are a problem I can't understand.

One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation

Maybe I know why Abstract Factory pattern use composition and delegates to create object, but I can't understand why Factory Method pattern uses inheritance to create concrete class objects.


回答1:


Abstract Factory

public interface IMyFactory
{
    IMyClass CreateMyClass(int someParameter);
}

Usage:

public class SomeOtherClass
{
    private readonly IMyFactory factory;

    public SomeOtherClass(IMyFactory factory)
    {
        this.factory = factory;
    }

    public void DoSomethingInteresting()
    {
        var mc = this.factory.CreateMyClass(42);
        // Do something interesting here
    }
}

Notice that SomeOtherClass relies on Composition to be composed with an IMyFactory instance.

Factory Method

public abstract class SomeOtherClassBase
{
    public void DoSomethingInteresting()
    {
        var mc = this.CreateMyClass(42);
        // Do something interesting here
    }

    protected abstract IMyClass CreateMyClass(int someParameter)
}

Usage:

public class SomeOtherClass2 : SomeOtherClassBase
{   
    protected override IMyClass CreateMyClass(int someParameter)
    {
        // Return an IMyClass instance from here
    }
}

Notice that this example relies on inheritance to work.



来源:https://stackoverflow.com/questions/22643449/abstract-factory-vs-factory-method-composition-vs-inplement

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