抽象工厂、工厂方法、构建器

发布于 2024-09-18 06:27:04 字数 344 浏览 11 评论 0原文

这似乎是一个骗局,但请耐心等待 - 我保证我已阅读相关帖子(以及 GOF 书)。

在读完所有内容后,我仍然不清楚何时使用抽象工厂、工厂方法或构建器。我相信在我看到一个简单的问题示例后,它最终会被理解,这个问题最好由构建者来解决,而使用抽象工厂显然是愚蠢的。

您能否提供一个简单的示例,其中您将清楚地使用一种模式而不是其他模式?

我知道如果这个例子太简单,这可能会归结为一个意见问题,但我希望如果有人可以的话,那个人就是这样。

谢谢。

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).

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.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

岁月流歌 2024-09-25 06:27:04

构建器可以帮助您构建复杂的对象。一个示例是 StringBuilder 类 (JavaC#) ,逐段构建最终的字符串。一个更好的例子是 UriComponentsBuilder< Spring 中的 /a> 可以帮助您构建 URI。

工厂方法一次性为您提供一个完整的对象(与构建器相反)。基类定义一个返回接口(或超类)引用的抽象方法,并将对象的具体创建推迟到子类。

抽象工厂是一个接口(或抽象类),用于创建许多不同的相关对象。一个很好的例子(在 .NET 中)是 DbProviderFactory 类,用于创建给定数据库提供程序(oracle、sql server 等)的相关对象(连接、命令等),具体取决于其具体实现。

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.

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.

绿光 2024-09-25 06:27:04

构建器

// Builder encapsulates construction of other object. Building of the object can be done in multiple steps (methods)
public class ConfigurationBuilder
{
  // Each method adds some configuration part to internally created Configuration object
  void AddDbConfiguration(...);
  void AddSmtpConfiguration(...);
  void AddWebServicesConfiguration(...);
  void AddWebServerConfiguration(...);

  // Returns built configuration
  Configuration GetConfiguration();
}

工厂方法

// Factory method is declared in base class or interface. Subclass defines what type is created by factory method.
public interface ICacheProvider
{
  ISession CreateCache(); // Don't have to return new instance each time - such decission is part of implementation in derived class.
}

public class InMemoryCacheProvider : ICacheProvider
{ ... }

public class DbStoredCacheProvider : ICacheProvider
{ ... }

// Client code
ICacheProvider provider = new InMemoryCacheProvider
ICache cache = provider.CreateCache(); 

抽象工厂

// Abstract factory defines families of platform classes - you don't need to specify each platform class on the client.
public interface IDbPlatform
{
  // It basically defines many factory methods for related classes
  IDbConnection CreateConnection();
  IDbCommand CreateCommand();
  ...
}

// Abstract factory implementation - single class defines whole platform
public class OraclePlatfrom : IDbPlatform
{ ... }

public class MySqlPlatform : IDbPlatform
{ ... }

// Client code:
IDbPlatform platform = new OraclePlatform();
IConnection connection = platform.CreateConnection(); // Automatically Oracle related
...

Builder

// Builder encapsulates construction of other object. Building of the object can be done in multiple steps (methods)
public class ConfigurationBuilder
{
  // Each method adds some configuration part to internally created Configuration object
  void AddDbConfiguration(...);
  void AddSmtpConfiguration(...);
  void AddWebServicesConfiguration(...);
  void AddWebServerConfiguration(...);

  // Returns built configuration
  Configuration GetConfiguration();
}

Factory method

// Factory method is declared in base class or interface. Subclass defines what type is created by factory method.
public interface ICacheProvider
{
  ISession CreateCache(); // Don't have to return new instance each time - such decission is part of implementation in derived class.
}

public class InMemoryCacheProvider : ICacheProvider
{ ... }

public class DbStoredCacheProvider : ICacheProvider
{ ... }

// Client code
ICacheProvider provider = new InMemoryCacheProvider
ICache cache = provider.CreateCache(); 

Abstract Factory

// Abstract factory defines families of platform classes - you don't need to specify each platform class on the client.
public interface IDbPlatform
{
  // It basically defines many factory methods for related classes
  IDbConnection CreateConnection();
  IDbCommand CreateCommand();
  ...
}

// Abstract factory implementation - single class defines whole platform
public class OraclePlatfrom : IDbPlatform
{ ... }

public class MySqlPlatform : IDbPlatform
{ ... }

// Client code:
IDbPlatform platform = new OraclePlatform();
IConnection connection = platform.CreateConnection(); // Automatically Oracle related
...
喜你已久 2024-09-25 06:27:04

抽象工厂、工厂方法、构建器:所有这些模式都是创建模式,它们是处理对象创建机制的设计模式,试图以适合的方式创建对象情况。

工厂方法:

  1. 它定义了一个用于创建对象的接口,但让子类决定实例化哪个类
  2. 我们创建一个对象,而不向客户端暴露创建逻辑< /em> 并使用公共接口(或抽象类)引用新创建的对象
  3. 通过消除将特定于应用程序的类绑定到代码中的需要来提供松散耦合。代码仅与接口或抽象类交互
  4. 它可以使用继承或子类化来实现目的

    要点:您将创建一个界面并创建一个界面。这些接口的具体实现。在工厂方法中,根据条件,您将获得公共接口的具体实现。

抽象工厂:

  1. 提供一个用于创建相关或依赖对象系列的接口,而无需指定它们的具体类
  2. 封装的层次结构:许多可能的“平台” `,以及构建一套“产品”
  3. 抽象工厂类通常使用工厂方法实现,但也可以使用原型

Builder:

  1. Builder 实现模式使用简单对象并使用逐步方法构建复杂对象
  2. 在这种情况下替换为工厂方法/抽象工厂:从客户端程序传递到工厂类的参数太多可能容易出错
  3. 一些参数可能是可选的,与 Factory 不同,Factory 强制发送所有参数

Java 中 Builder 设计模式指南

  1. 在类中创建一个名为 Builder 的静态嵌套类,其对象将由Builder
  2. Builder 类将具有与原始类完全相同的字段集
  3. Builder 类将公开添加成分的方法。每个方法将返回相同的 Builder 对象。构建器将通过每个方法调用而丰富。
  4. Builder.build() 方法会将所有构建器字段值复制到实际类中并返回 Item 类的对象
  5. Item 类(我们为其创建 Builder 的类)应该有私有构造函数来创建其对象来自 build() 方法并防止外部访问其构造函数。

相关文章:

设计模式:工厂、工厂方法与抽象工厂

将构建器保留在单独的类中(流畅的界面)

有用的链接:

sourcemaking< /a> 设计模式

Abstract Factory, Factory Method, Builder : All these patterns are creational patterns,which are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

Factory method:

  1. It defines an interface for creating an object, but let subclasses decide which class to instantiate
  2. We create an object without exposing the creation logic to the client and refer to newly created object using a common interface ( or an abstract classes)
  3. Provides loose-coupling by eliminating the need to bind application-specific classes into the code. Code interacts only with interface or abstract class
  4. It may use inheritance or sub classing to achieve the purpose

    Key note: You will create an interface & specific implementation of these interfaces. In Factory method, depending on condition, you will get concrete implementation of common interface.

Abstract Factory:

  1. Provide an interface for creating families of related or dependent objects without specifying their concrete classes
  2. A hierarchy that encapsulates: many possible "platforms"`, and the construction of a suite of "products"
  3. Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype

Builder:

  1. Builder pattern builds a complex object using simple objects and using a step by step approach
  2. Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
  3. Some of the parameters might be optional unlike in Factory which forces to send all parameters

Guidelines for Builder design pattern in Java

  1. Make a static nested class called Builder inside the class whose object will be build by Builder
  2. Builder class will have exactly same set of fields as original class
  3. Builder class will expose method for adding ingredients. Each method will return same Builder object. Builder will be enriched with each method call.
  4. Builder.build() method will copy all builder field values into actual class and return object of Item class
  5. Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.

Related posts:

Design Patterns: Factory vs Factory method vs Abstract Factory

Keeping builder in separate class (fluent interface)

Useful links:

sourcemaking design-patterns

我喜欢麦丽素 2024-09-25 06:27:04

抽象工厂模式使用(工厂)子类化来生成其他对象(非工厂)。抽象工厂还设想生成的对象属于并行层次结构(例如,为了处理平台独立性,每个平台一个层次结构)。

Builder 模式使用子类化来生成“输出”——根本不一定是对象。 GOF 示例让生成器生成文本输出(标记或其他)。

工厂方法模式与其他两种模式不同,将“创建者”分为抽象和具体实现(因此强调它属于框架实现)。与抽象工厂一样,它处理实际对象的制作。

这三个都非常相似,因为它们都使用子类化。子类化是它们的突出品质,它隐藏了细微的差异(如上所述),因此许多人很难看到差异。

The Abstract Factory pattern uses subclassing (of factories) to produce other objects (non-factories). Abstract Factory also envisions that the objects produced belong to parallel hierarchies (e.g. to handle platform independance, one hierarchy for each platform).

The Builder pattern uses subclassing to produce "output" - which is not necessarily objects at all. The GOF example has the Builder producing text output (markup or otherwise).

The Factory Method pattern, unlike the other two, divides the "creator" into an abstract and concrete implementation (thus the emphasis on it belonging to a framework implementation). Like Abstract Factory, it deals with making actual objects.

All three are highly similar, because they all use subclassing. It is the subclassing that is the outstanding quality of them all, which hides the subtle differences (outlined above) and thus many people have difficulty seeing the differences.

终止放荡 2024-09-25 06:27:04

抽象工厂对于测试驱动开发和减少耦合特别有帮助。

例如,在 C# 中:

public class Worker
{
    public IConsumerFactory Factory { get; set; }

    private IResource resource;

    public DoWork()
    {
        IConsumer consumer = Factory.CreateConsumer();
        consumer.Consume(resource);
    }
}

public interface IConsumerFactory
{
    IConsumer CreateConsumer();
}

public interface IConsumer
{
    void Consume(IResource resource);
}

public class DefaultConsumerFactory : IConsumerFactory
{
    public IConsumer CreateConsumer()
    {
        return new DefaultConsumer();
    }
}

public class DefaultConsumer : IConsumer
{
    public void Consume(IResource resource)
    {
      ... Do Work ...
    }
}

这样,您可以使用依赖注入来注入生产代码的默认实现,然后您可以轻松模拟工厂及其创建的对象。

Abstract Factory is particularly helpful for test driven development and reducing coupling.

For example, in C#:

public class Worker
{
    public IConsumerFactory Factory { get; set; }

    private IResource resource;

    public DoWork()
    {
        IConsumer consumer = Factory.CreateConsumer();
        consumer.Consume(resource);
    }
}

public interface IConsumerFactory
{
    IConsumer CreateConsumer();
}

public interface IConsumer
{
    void Consume(IResource resource);
}

public class DefaultConsumerFactory : IConsumerFactory
{
    public IConsumer CreateConsumer()
    {
        return new DefaultConsumer();
    }
}

public class DefaultConsumer : IConsumer
{
    public void Consume(IResource resource)
    {
      ... Do Work ...
    }
}

This way, you can use dependency injection to inject the default implementations for production code, and then you can easily mock the factory and the objects it creates.

雅心素梦 2024-09-25 06:27:04
  • 工厂方法模式 - 当您想要构建复杂对象系列时。
  • 对象构建器模式 - 当您希望允许用户将其自定义实现插入您的框架时,

请访问以下网址了解更多详细信息。

http://xeon2k.wordpress.com

  • Factory Method pattern - When you want to build family of complex objects.
  • Object builder pattern - When you want to allow user to plugin their custom implementation into your framework

Please visit the following url for more details.

http://xeon2k.wordpress.com

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文