一、Creational patterns 创建模式
Abstract factory (recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)
注意到都是 #newInstance(),一般是这是个静态方法,返回一个类本身的工厂对象。然后这个工厂对象可以去创建其他的抽象类型,最后创建什么对象要看抽象工厂的实现类。
创建一组有关联的对象实例。这个模式在JDK中也是相当的常见,还有很多的framework例如Spring。我们很容易找到这样的实例。
javax.xml.parsers.DocumentBuilderFactory#newInstance()
javax.xml.transform.TransformerFactory#newInstance()
javax.xml.xpath.XPathFactory#newInstance()
Builder (recognizeable by creational methods returning the instance itself)
返回对象本身。主要用来简化一个复杂的对象的创建。
java.lang.StringBuilder#append()
(unsynchronized)java.lang.StringBuffer#append()
(synchronized)java.nio.ByteBuffer#put()
(also onCharBuffer
,ShortBuffer
,IntBuffer
,LongBuffer
,FloatBuffer
andDoubleBuffer
)javax.swing.GroupLayout.Group#addComponent()
- All implementations of
java.lang.Appendable
Factory method (recognizeable by creational methods returning an implementation of an abstract/interface type)
简单来说,按照需求返回一个类型的实例。
以下几个类都是抽象类,而方法是静态方法,也就是可以用这些抽象类的静态方法返回一个实例,实例的类型是这个抽象类型,具体是实现在静态方法里面。
java.util.Calendar#getInstance()
java.util.ResourceBundle#getBundle()
java.text.NumberFormat#getInstance()
java.nio.charset.Charset#forName()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String)
(Returns singleton object per protocol)
Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)
使用自己的实例创建另一个实例。有时候,创建一个实例然后再把已有实例的值拷贝过去,是一个很复杂的动作。所以,使用这个模式可以避免这样的复杂性。
java.lang.Object#clone()
(the class has to implementjava.lang.Cloneable
)
Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)
二、Structural patterns 结构模式
Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)
java.util.Arrays#asList()
java.io.InputStreamReader(InputStream)
(returns aReader
)java.io.OutputStreamWriter(OutputStream)
(returns aWriter
)javax.xml.bind.annotation.adapters.XmlAdapter#marshal()
and#unmarshal()
Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)
- None comes to mind yet. A fictive example would be
new LinkedHashMap(LinkedHashSet<K>, List<V>)
which returns an unmodifiable linked map which doesn‘t clone the items, but uses them. Thejava.util.Collections#newSetFromMap()
andsingletonXXX()
methods however comes close.
Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)
java.awt.Container#add(Component)
(practically all over Swing thus)javax.faces.component.UIComponent#getChildren()
(practically all over JSF UI thus)
Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)
- All subclasses of
java.io.InputStream
,OutputStream
,Reader
andWriter
have a constructor taking an instance of same type. java.util.Collections
, thecheckedXXX()
,synchronizedXXX()
andunmodifiableXXX()
methods.javax.servlet.http.HttpServletRequestWrapper
andHttpServletResponseWrapper
Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)
javax.faces.context.FacesContext
, it internally uses among others the abstract/interface typesLifeCycle
,ViewHandler
,NavigationHandler
and many more without that the enduser has to worry about it (which are however overrideable by injection).javax.faces.context.ExternalContext
, which internally usesServletContext
,HttpSession
,HttpServletRequest
,HttpServletResponse
, etc.
Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)
Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)
java.lang.reflect.Proxy
java.rmi.*
, the whole API actually.
The Wikipedia example is IMHO a bit poor, lazy loading has actually completely nothing to do with the proxy pattern at all.
三、Behavioral patterns 行为模式
Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method inanother implementation of same abstract/interface type in a queue)
Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)
命令模式将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。同时命令模式支持可撤销的操作。
命令模式可以将请求的发送者和接收者之间实现完全的解耦,发送者和接收者之间没有直接的联系,发送者只需要知道如何发送请求命令即可,其余的可以一概不管,甚至命令是否成功都无需关心。同时我们可以非常方便的增加新的命令,但是可能就是因为方便和对请求的封装就会导致系统中会存在过多的具体命令类。
- All implementations of
java.lang.Runnable
- All implementations of
javax.swing.Action
Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)
所谓解释器模式就是定义语言的文法,并且建立一个解释器来解释该语言中的句子。解释器模式描述了如何构成一个简单的语言解释器,主要应用在使用面向对象语言开发的编译器中。它描述了如何为简单的语言定义一个文法,如何在该语言中表示一个句子,以及如何解释这些句子。
java.util.Pattern
java.text.Normalizer
- All subclasses of
java.text.Format
- All subclasses of
javax.el.ELResolver
Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)
所谓迭代器模式就是提供一种方法顺序访问一个聚合对象中的各个元素,而不是暴露其内部的表示。迭代器模式是将迭代元素的责任交给迭代器,而不是聚合对象,我们甚至在不需要知道该聚合对象的内部结构就可以实现该聚合对象的迭代。
- All implementations of
java.util.Iterator
(thus among others alsojava.util.Scanner
!). - All implementations of
java.util.Enumeration
Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)
所谓中介者模式就是用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
很多池技术,中间件,可以理解为中介者模式。
Timer是一个线程,对每个TimerTask启动一个线程。。。
java.util.Timer
(allscheduleXXX()
methods)java.util.concurrent.Executor#execute()
java.util.concurrent.ExecutorService
(theinvokeXXX()
andsubmit()
methods)java.util.concurrent.ScheduledExecutorService
(allscheduleXXX()
methods)java.lang.reflect.Method#invoke()
Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)
备忘录模式就是一种后悔药,它给我们的软件提供后悔药的机制,通过它可以使系统恢复到某一特定的历史状态。
备忘录模式就是在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。
java.util.Date
(the setter methods do that,Date
is internally represented by along
value)- All implementations of
java.io.Serializable
- All implementations of
javax.faces.component.StateHolder
Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)
观察者模式定义了对象之间的一对多依赖关系,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并且自动更新。
java.util.Observer
/java.util.Observable
(rarely used in real world though)- All implementations of
java.util.EventListener
(practically all over Swing thus) javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener
State (recognizeable by behavioral methods which changes its behaviour depending on the instance‘s state which can be controlled externally)
在很多情况下我们对象的行为依赖于它的一个或者多个变化的属性,这些可变的属性我们称之为状态,也就是说行为依赖状态,即当该对象因为在外部的互动而导致他的状态发生变化,从而它的行为也会做出相应的变化。对于这种情况,我们是不能用行为来控制状态的变化,而应该站在状态的角度来思考行为,即是什么状态就要做出什么样的行为。这个就是状态模式。
所以状态模式就是允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
LifeCycle生命周期的类需要应对生命周期中很多不同的状态。
以状态为原子来改变它的行为,而不是通过行为来改变状态。
javax.faces.lifecycle.LifeCycle#execute()
(controlled byFacesServlet
, the behaviour is dependent on current phase (state) of JSF lifecycle)
Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)
所以策略模式就是定义了算法族,分别封装起来,让他们之前可以互相转换,此模式然该算法的变化独立于使用算法的客户。
java.util.Comparator#compare()
, executed by among othersCollections#sort()
.javax.servlet.http.HttpServlet
, theservice()
and alldoXXX()
methods takeHttpServletRequest
andHttpServletResponse
and the implementor has to process them (and not to get hold of them as instance variables!).javax.servlet.Filter#doFilter()
Template method (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)
- All non-abstract methods of
java.io.InputStream
,java.io.OutputStream
,java.io.Reader
andjava.io.Writer
. - All non-abstract methods of
java.util.AbstractList
,java.util.AbstractSet
andjava.util.AbstractMap
. javax.servlet.http.HttpServlet
, all thedoXXX()
methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You‘re free to implement none or any of them.
Visitor (recognizeable by two different abstract/interface types which has methods definied which takes each theother abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)
javax.lang.model.element.AnnotationValue
andAnnotationValueVisitor
javax.lang.model.element.Element
andElementVisitor
javax.lang.model.type.TypeMirror
andTypeVisitor
四、设计原则
1、单一职责原则
一个类,只有一个引起它变化的原因。应该只有一个职责。每一个职责都是变化的一个轴线,如果一个类有一个以上的职责,这些职责就耦合在了一起。这会导致脆弱的设计。当一个职责发生变化时,可能会影响其它的职责。另外,多个职责耦合在一起,会影响复用性。例如:要实现逻辑和界面的分离。from:百度百科
2、开闭原则(Open Close Principle)
开闭原则就是说对扩展开放,对修改关闭。在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。所以一句话概括就是:为了使程序的扩展性好,易于维护和升级。想要达到这样的效果,我们需要使用接口和抽象类,后面的具体设计中我们会提到这点。
3、里氏代换原则(Liskov Substitution Principle)
里氏代换原则(Liskov Substitution Principle LSP)面向对象设计的基本原则之一。 里氏代换原则中说,任何基类可以出现的地方,子类一定可以出现。 LSP是继承复用的基石,只有当衍生类可以替换掉基类,软件单位的功能不受到影响时,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为。里氏代换原则是对“开-闭”原则的补充。实现“开-闭”原则的关键步骤就是抽象化。而基类与子类的继承关系就是抽象化的具体实现,所以里氏代换原则是对实现抽象化的具体步骤的规范。from:百度百科
4、依赖倒转原则(Dependence Inversion Principle)
所谓依赖倒置原则(Dependence Inversion Principle)就是要依赖于抽象,不要依赖于具体。简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模块间的耦合。
实现开闭原则的关键是抽象化,并且从抽象化导出具体化实现,如果说开闭原则是面向对象设计的目标的话,那么依赖倒转原则就是面向对象设计的主要手段。 from:百度百科
5、接口隔离原则(Interface Segregation Principle)
这个原则的意思是:使用多个隔离的接口,比使用单个接口要好。还是一个降低类之间的耦合度的意思,从这儿我们看出,其实设计模式就是一个软件的设计思想,从大型软件架构出发,为了升级和维护方便。所以上文中多次出现:降低依赖,降低耦合。
6、合成复用原则(Composite Reuse Principle)
合成复用原则就是指在一个新的对象里通过关联关系(包括组合关系和聚合关系)来使用一些已有的对象,使之成为新对象的一部分;新对象通过委派调用已有对象的方法达到复用其已有功能的目的。简言之:要尽量使用组合/聚合关系,少用继承。
7、迪米特法则(最少知道原则)(Demeter Principle)
为什么叫最少知道原则,就是说:一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。也就是说一个软件实体应当尽可能少的与其他实体发生相互作用。这样,当一个模块修改时,就会尽量少的影响其他的模块,扩展会相对容易,这是对软件实体之间通信的限制,它要求限制软件实体之间通信的宽度和深度。
参考:
英文原文:Examples of GoF Design Patterns
设计模式总结
设计模式读书笔记-----命令模式
JDK里的设计模式