设计模式Java实现示例

jopen 7年前

用Java实现的设计模式实现示例。

Abstract Factory

Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

设计模式Java实现示例

Applicability: Use the Abstract Factory pattern when

  • a system should be independent of how its products are created, composed and represented
  • a system should be configured with one of multiple families of products
  • a family of related product objects is designed to be used together, and you need to enforce this constraint
  • you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations

Builder

Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations.

设计模式Java实现示例

Applicability: Use the Builder pattern when

  • the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled
  • the construction process must allow different representations for the object that's constructed

Factory Method

Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

设计模式Java实现示例

Applicability: Use the Factory Method pattern when

  • a class can't anticipate the class of objects it must create
  • a class wants its subclasses to specify the objects it creates
  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate

Prototype

Intent: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

设计模式Java实现示例

Applicability: Use the Prototype pattern when a system should be independent of how its products are created, composed and represented; and

  • when the classes to instantiate are specified at run-time, for example, by dynamic loading; or
  • to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or
  • when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state

https://github.com/iluwatar/java-design-patterns