设计模式概览

本篇文章记录我所理解和掌握的在 《Design Patterns》 书中提及的一些设计模式,及其在 JDK 和 Spring 中的一些实现。


创建型 Creational Patterns

抽象工厂模式 Abstract Factory Pattern

意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • org.springframework.beans.factory.FactoryBean#getObject()

生成器模式 Builder Pattern

意图:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。Separate the construction of a complex object from its representation so that the same construction process can create different representations.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.StringBuilder & java.lang.StringBuffer
  • org.springframework.boot.web.client.RestTemplateBuilder
  • org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder
  • org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder

工厂方法模式 Factory Method Pattern

意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.Object#getClass() & java.lang.Object#toString()
  • javax.sql.DataSource#getConnection()
  • java.util.concurrent.ThreadFactory
  • org.springframework.beans.factory.FactoryBean

原型模式 Prototype Pattern

意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.Object#clone()

单例模式 Singleton Pattern

意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。Ensure a class only has one instance, and provide a global point of access to it.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.Runtime#getRuntime()

结构型 Structural Patterns

适配器模式 Adapter Pattern

意图:将一个类的接口转换成客户希望的另外一个接口。Adapter 使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.util.Arrays#asList(Object[])
  • java.lang.Throwable#Throwable(String, Throwable)
  • java.io.InputStreamReader & java.io.OutputStreamWriter
  • java.util.Collections#enumeration(Collection) & java.util.Collections#list(Enumeration)

桥接模式 Bridge Pattern

意图:将抽象部分与它的实现部分分离,使它们都可以独立地变化。Decouple an abstraction from its implementation so that the two can vary independently.

参考:Wikipediajava-design-patterns菜鸟教程

实现:待续

组合模式 Composite Pattern

意图:将对象组合成树形结构以表示 “部分-整体” 的层次结构。Composite 使得用户对单个对象和组合对象的使用具有一致性。Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

参考:Wikipediajava-design-patterns菜鸟教程

实现:待续

装饰器模式 Decorator Pattern

意图:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator 模式相比生成子类更为灵活。Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.io.BufferedInputStream & java.io.DataInputStream
  • java.util.Collections#synchronizedCollection(Collection) & java.util.Collections##unmodifiableCollection(Collection)
  • javax.servlet.http.HttpServletRequestWrapper
  • org.springframework.beans.BeanWrapper

外观模式 Facade Pattern

意图:为子系统中的一组接口提供一个一致的界面。Facade 定义了一个高层接口,这个接口使得这一子系统更加容易使用。Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

参考:Wikipediajava-design-patterns菜鸟教程

实现:待续

享元模式 Flyweight Pattern

意图:运用共享技术有效地支持大量细粒度的对象。Use sharing to support large numbers of fine-grained objects efficiently.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.String
  • java.lang.Integer#valueOf(int)

代理模式 Proxy Pattern

意图:为其它对象提供一种代理以控制对这个对象的访问。Provide a surrogate or placeholder for another object to control access to it.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.reflect.Proxy
  • org.springframework.aop.framework.AopProxy

行为型 Behavioral Patterns

责任链模式 Chain-of-Responsibility Pattern

意图:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.util.logging.Logger#log(Level, String)
  • javax.servlet.Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  • org.springframework.web.servlet.HandlerInterceptor#preHandle(HttpServletRequest, HttpServletResponse, Object)

命令模式 Command Pattern

意图:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤消的操作。Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.Runnable#run()
  • org.springframework.web.servlet.HandlerExecutionChain

解释器模式 Interpreter Pattern

意图:给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.util.regex.Pattern#compile(String)
  • org.springframework.scheduling.annotation.Scheduled#cron()

迭代器模式 Iterator Pattern

意图:提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示。Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.sql.ResultSet
  • java.util.Iterator
  • java.util.Enumeration

中介者模式 Mediator Pattern

意图:用一个中介对象来封装一系列的对象交互。Mediator 使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring toeach other explicitly, and it lets you vary their interaction independently.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.util.concurrent.Executor#execute(Runnable)
  • java.util.concurrent.ExecutorService#submit(Callable) & java.util.concurrent.ExecutorService#submit(Runnable)

备忘录模式 Memento Pattern

意图:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.util.Date

观察者模式 Observer Pattern

意图:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.util.Observer#update(Observable, Object)
  • java.util.Observable#notifyObservers()
  • org.springframework.context.ApplicationEvent
  • org.springframework.context.ApplicationEventPublisher

状态模式 State Pattern

意图:允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

参考:Wikipediajava-design-patterns菜鸟教程

实现:待续

策略模式 Strategy Pattern

意图:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。Strategy 使得算法可独立于使用它的客户而变化。Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.lang.Comparable#compareTo(Object)
  • java.lang.Object#hashCode() & java.lang.Object#equals(Object)
  • org.springframework.core.io.ResourceLoader#getResource(String)
  • org.springframework.web.accept.ContentNegotiationStrategy#resolveMediaTypes(NativeWebRequest)

模板方法模式 Template Method Pattern

意图:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Template Method 使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • org.springframework.context.support.AbstractApplicationContext#refresh()

访问者模式 Visitor Pattern

意图:表示一个作用于某对象结构中的各元素的操作。Visitor 使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

参考:Wikipediajava-design-patterns菜鸟教程

实现:

  • java.nio.file.FileVisitor
  • org.springframework.beans.factory.config.BeanDefinitionVisitor