关于设计模式:抽象工厂与工厂方法:组合还是实施?

Abstract Factory vs Factory method: Composition vs Inplement?

本问题已经有最佳答案,请猛点这里访问。

我读过很多关于抽象工厂和工厂方法不同的帖子,但有一个问题我不明白。

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

也许我知道抽象工厂模式为什么使用组合和委托来创建对象,但我不明白工厂方法模式为什么使用继承来创建具体的类对象。


抽象工厂

1
2
3
4
public interface IMyFactory
{
    IMyClass CreateMyClass(int someParameter);
}

用途:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
    }
}

注意,SomeOtherClass依赖组合与IMyFactory实例组成。

工厂法

1
2
3
4
5
6
7
8
9
10
public abstract class SomeOtherClassBase
{
    public void DoSomethingInteresting()
    {
        var mc = this.CreateMyClass(42);
        // Do something interesting here
    }

    protected abstract IMyClass CreateMyClass(int someParameter)
}

用途:

1
2
3
4
5
6
7
public class SomeOtherClass2 : SomeOtherClassBase
{  
    protected override IMyClass CreateMyClass(int someParameter)
    {
        // Return an IMyClass instance from here
    }
}

请注意,这个例子依赖继承来工作。