抽象工厂,工厂方法,生成器 [英] Abstract Factory, Factory Method, Builder
问题描述
It may seem as if this is question is a dupe, but please bear with me - I promise I've read the related posts (and the GOF book).
阅读完所有内容后,我仍然不清楚何时使用抽象工厂,工厂方法或生成器.我相信在我看到一个简单的问题示例(最好是由 builder 处理)的问题之后,它最终会陷入困境,并且使用诸如 abstract factory这样的工厂显然很愚蠢. .
After everything I've read, I still don't have it clear when to use an Abstract Factory, a Factory Method, or a Builder. I believe it will finally sink in after I see a simple example of a problem which is best approached by, say, a builder and it would be clearly silly to use, say, an abstract factory.
您能否提供一个简单的示例,明确使用一个模式而不使用其他模式?
Can you provide a simple example where you would clearly use one pattern and not the others?
我知道,如果示例太简单,这可能归结为一个观点问题,但是我希望,如果有人可以,那么这个人就是这样.
I understand it may boil down to a matter of opinion if the example is too simple, but I'm hopeful that if anybody can, that person is in SO.
谢谢.
推荐答案
构建器可帮助您构建复杂的对象.一个示例是StringBuilder
类( Java , C#),它会生成最终版本一块一块地.更好的示例是 UriComponentsBuilder 在Spring中,它可以帮助您构建URI.
A builder helps you construct a complex object. An example is the StringBuilder
class (Java, C#), which builds the final string piece by piece. A better example is the UriComponentsBuilder in Spring, which helps you build a URI.
工厂方法可以一次完成一个完整的对象(与生成器相对).基类定义单个抽象方法,该方法返回接口(或超类)引用,并将对象的具体创建推迟到子类.
A factory method gives you a complete object in one shot (as opposed to the builder). A base class defines a single abstract method that returns an interface (or super class) reference, and defers the concrete creation of the object to subclasses.
抽象工厂是创建许多不同相关对象的接口(或抽象类).一个很好的例子(在.NET中)是 DbProviderFactory
类,用于根据给定的数据库提供程序(oracle,sql server等)创建相关对象(连接,命令等).
An abstract factory is an interface (or abstract class) to create many different related objects. A good example (in .NET) is the DbProviderFactory
class, that serves to create related objects (connections, commands, ...) to a given database provider (oracle, sql server, ...), depending on its concrete implementation.
这篇关于抽象工厂,工厂方法,生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!