Abstract Factory, Factory Method, Builder

后端 未结 6 1147
清歌不尽
清歌不尽 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:49

    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

提交回复
热议问题