本文介绍了抽象工厂与工厂方法:组成与继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我已经阅读了很多有关Abstract Factory和Factory方法之间的区别的文章,但是有一个我无法理解的问题。I have read a lot of posts about different between Abstract Factory and Factory method, but there are a problem I can't understand.也许我知道为什么Abstract Factory模式使用合成和委托来创建对象,但是我不明白为什么Factory方法模式使用继承来创建具体的类对象。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.此问题与抽象工厂是什么或工厂方法是什么有关,因此没有答案此处This question is not about what abstract factory is or what factory method is and hence does not have answer here这就是为什么工厂方法似乎使用继承因为客户端也可以直接调用工厂方法。请将其取消标记为重复项。It is about why factory method seems to use inheritance when a client can call factory method directly too. Please unmark it as duplicate.推荐答案 抽象工厂public interface IMyFactory{ IMyClass CreateMyClass(int someParameter);}用法: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 依赖于Composition与 IMyFactory 实例组成。Notice that SomeOtherClass relies on Composition to be composed with an IMyFactory instance. 工厂方法public abstract class SomeOtherClassBase{ public void DoSomethingInteresting() { var mc = this.CreateMyClass(42); // Do something interesting here } protected abstract IMyClass CreateMyClass(int someParameter)}用法: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. 这篇关于抽象工厂与工厂方法:组成与继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-23 09:15