Abstract Factory, Factory Method, Builder

后端 未结 6 1150
清歌不尽
清歌不尽 2021-01-30 09:21

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

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 09:44

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

提交回复
热议问题