抽象工厂,工厂方法,生成器

Esc*_*alo 32 language-agnostic design-patterns builder factory-method abstract-factory

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

在我读完所有内容之后,我仍然没有清楚何时使用抽象工厂,工厂方法或构建器.我相信它会在我看到一个问题的简单例子之后陷入困境,这个问题最好由建筑商来处理,而使用抽象工厂显然是愚蠢的.

你能提供一个简单的例子,你可以清楚地使用一种模式而不是其他模式吗?

我理解,如果这个例子过于简单,可能归结为意见问题,但我希望如果有人可以,那个人就是这样.

谢谢.

Jor*_*dão 53

构建器可帮助您构造复杂对象.一个例子是StringBuilder类(Java,C#),它逐个构建最终的字符串.一个更好的例子是Spring中的UriComponentsBuilder,它可以帮助您构建URI.

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

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


Lad*_*nka 8

生成器

// 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();
}
Run Code Online (Sandbox Code Playgroud)

工厂方法

// 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(); 
Run Code Online (Sandbox Code Playgroud)

抽象工厂

// 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
...
Run Code Online (Sandbox Code Playgroud)