问题描述
我正在学习GOF Java设计模式,我想看看它们的一些现实生活例子. Java的核心库中这些设计模式的一些好例子是什么?
推荐答案
您可以在 wikipedia"> wikipedia "> wikipedia "> wikipedia .它还提到GOF提到了哪些模式.我将在这里总结它们,并尝试分配尽可能多的模式实现,在Java SE和Java EE API中找到.
创建模式
抽象出厂 (可通过创建方法返回工厂本身,反过来可以用来创建另一种抽象/接口类型)
建筑商 (通过创建方法返回实例本身可以识别)
- java.lang.StringBuilder#append() java.lang.StringBuilder#append() java.lang.StringBuilder#append() (不同步)
- java.lang.StringBuffer#append() java.lang.StringBuffer#append()
(同步) - java.nio.ByteBuffer#put() java.nio.ByteBuffer#put() java.nio.ByteBuffer#put() (也在 CharBuffer , ShortBuffer ShortBuffer , IntBuffer IntBuffer , LongBuffer LongBuffer , FloatBuffer 和 DoubleBuffer DoubleBuffer )
- java.lang.Appendable java.lang.Appendable 的所有实现
- java.util.stream.Stream.Builder java.util.stream.Stream.Builder
工厂方法 (可通过创建方法识别的创造方法识别的实现摘要/接口类型)
- java.util.Calendar#getInstance() java.util.Calendar#getInstance()
-
java.util.ResourceBundle#getBundle() - java.text.NumberFormat#getInstance() java.text.NumberFormat#getInstance()
- java.nio.charset.Charset#forName()
- java.net.URLStreamHandlerFactory#createURLStreamHandler(String) java.net.URLStreamHandlerFactory#createURLStreamHandler(String) 根据协议的对象)
- java.util.EnumSet#of() java.util.EnumSet#of() java.util.EnumSet#of() 一个>
- prototype (通过创建方法返回 具有相同属性的实例)
- java.lang.Object#clone() (课程必须实现 java.lang.Cloneable )
singleton
实例(通常是本身)) - java.lang.Runtime#getRuntime() java.lang.Runtime#getRuntime()
- java.awt.Desktop#getDesktop() java.awt.Desktop#getDesktop()
- java.lang.System#getSecurityManager() java.lang.System#getSecurityManager()
结构模式
adapter
>不同的摘要/接口类型并返回自己的/另一个摘要/接口类型的实现 demantate/offrides 给定实例) -
- java.util.Collections#list()
- java.util.Collections#enumeration()
- java.io.InputStreamReader(InputStream) (返回A Reader)
- <<<<<<<<<
(返回A Writer) - #unmarshal()
bridge
(通过创造方法可识别,以不同的摘要/接口类型并返回自己的抽象/接口类型的实现,该类型 dem> demegates/use 给定实例) - 还没想到.一个虚构的示例是new LinkedHashMap(LinkedHashSet<K>, List<V>),它返回一个不可修道的链接映射,该地图不会克隆项目,但使用它们. 和 singletonXXX() 方法接近.
composite
(通过行为方法可识别的是采用相同摘要/接口类型到树结构中) - javax.faces.component.UIComponent#getChildren() javax.faces.component.UIComponent#getChildren() (实际上是JSF UI如此)
decorator (通过使用相同摘要/接口类型,添加其他行为)
- java.io.InputStream java.io.InputStream 的所有子类, OutputStream " http://docs.oracle.com/javase/8/docs/api/java/io/reader.html" rel =" noreferrer"> Reader 和 Writer 让一个构造函数使用相同类型的实例.
- java.util.Collections , a href =" http://docs.oracle.com/javase/8/docs/api/java/java/java/collections.html#checkedcollection-java.util.collection-java.collection-java.lang.lang.class.class.class- > checkedXXX() , synchronizedXXX() 和 unmodifiableXXX() 方法.
- javax.servlet.http.HttpServletRequestWrapper javax.servlet.http.HttpServletRequestWrapper javax.servlet.http.HttpServletRequestWrapper javax.servlet.http.HttpServletRequestWrapper href =" http://docs.oracle.com/javaee/7/api/javax/javax/servlet/http/httpservletresponsewrapper.html"
- javax.swing.JScrollPane
facade
(通过行为方法可识别,该行为使用<的行为方法, em>不同的独立摘要/接口类型) - javax.faces.context.FacesContext 使用摘要/接口类型 a>, ViewHandler , NavigationHandler 等等担心它(但是,注射可剥夺).
- javax.faces.context.ExternalContext 使用 ServletContext ServletContext , HttpSession , HttpServletRequest , HttpServletResponse 等,等等.
flyWeaight (通过创建方法返回一个被缓存的实例,一个可识别的方法,位" multiton"想法)
- java.lang.Integer#valueOf(int) java.lang.Integer#valueOf(int) (也可以在 Boolean , Byte , Character , Short , Long 和 BigDecimal )
proxy (通过创建方法可识别,以返回给定的给定方法实现了给定的实现摘要/接口类型依次委托/use a 不同的给定的摘要/接口类型的实现)
- java.lang.reflect.Proxy java.lang.reflect.Proxy /li>
- java.rmi.* /li>
- javax.ejb.EJB " https://stackoverflow.com/questions/255514361/when-using-ejb-does-each-managed-bean-get-get-cet-ist-en-ejb-instance"> explanation )
- javax.inject.Inject " https://stackoverflow.com/questions/29651008/field-getobj-returns-all-nulls-nulls-onmented-cdi-managed-beans-beans-while-while-manaly-i/29672591#29672591 "> explanation )
- javax.persistence.PersistenceContext
行为模式
责任链 > > (通过行为方法可识别(独立的方法)在中调用相同的方法 same same 摘要/接口类型中的实现)
command (通过摘要/接口类型的行为方法可以识别它在实现A 不同摘要/接口类型的实现中调用了一种方法,该类型已通过命令实现在创建过程中已封装)
解释器 (通过行为方法返回 结构上 给定实例/类型的不同实例/类型;请注意,解析/格式不是模式的一部分,确定模式以及如何应用它)
iterator (通过行为方法可识别不同的类型从队列)
- java.util.Iterator 的所有实现(因此,还有 java.util.Scanner ! ).
- java.util.Enumeration java.util.Enumeration 的所有实现
中间器/接口类型(通常使用命令模式)委托/使用给定实例)
- java.util.Timer java.util.Timer (全部scheduleXXX()方法)
- invokeXXX()和submit()方法)
- 所有scheduleXXX()方法)
- java.lang.reflect.Method#invoke()
memento (通过行为方法可识别,这些方法可以在内部改变全部实例)
- java.util.Date (setter方法做到这一点,Date由long value内部表示)
- java.io.Serializable java.io.Serializable 的所有实现
- javax.faces.component.StateHolder javax.faces.component.StateHolder 的所有实施
observer(或prublish/purplish/subscribe) > (通过行为方法可识别它在 另一个摘要/接口类型的实例上调用方法,具体取决于自己的状态)
- href =" http://docs.oracle.com/javase/8/docs/api/java/java/util/observable.html" rel =" noreferrer"> java.util.Observable (在现实世界中很少使用)
- java.util.EventListener java.util.EventListener (几乎全部摇摆)
- >
- >
- javax.faces.event.PhaseListener
state (通过行为方法可以识别其行为,其行为依赖于行为实例的状态可以在外部控制)
策略 (通过摘要/接口类型中的行为方法可以识别在实现A 不同的摘要/接口类型中,该方法已通过传递为作为方法参数中的方法参数)
- C109>和所有doXXX()方法采用HttpServletRequest和HttpServletResponse,并且实施者必须对其进行处理(并且不要将它们作为实例变量持有!).
- javax.servlet.Filter#doFilter()
template方法 (通过已经具有已经具有的行为方法识别的,默认"由抽象类型定义的行为)
- java.io.InputStream/a>, java.io.OutputStream a href =" http://docs.oracle.com/javase/8/docs/api/java/io/reader.html" rel =" noreferrer"> java.io.Reader 和 java.io.Writer .
.
- java.util.AbstractList java.util.AbstractList java.util.AbstractList java.util.AbstractList java.util.AbstractList/a>, java.util.AbstractSet a href =" http://docs.oracle.com/javase/8/docs/api/java/java/util/abstractmap.html" rel =" noreferrer"> java.util.AbstractMap .
.
- doXXX()方法默认情况下,将http 405"不允许的方法"发送给响应.您可以自由实施或任何一个.
访客 >摘要/接口类型,其定义的方法已定义,该方法将每种其他摘要/接口类型;一种实际上称为对方的方法,而另一个则在其上执行所需的策略) <
- javax.lang.model.element.AnnotationValue javax.lang.model.element.AnnotationValue and AnnotationValueVisitor AnnotationValueVisitor
- javax.lang.model.element.Element javax.lang.model.element.Element and ElementVisitor ElementVisitor
- >和 TypeVisitor
- java.nio.file.FileVisitor java.nio.file.FileVisitor SimpleFileVisitor SimpleFileVisitor
- VisitCallback VisitCallback
问题描述
I am learning GoF Java Design Patterns and I want to see some real life examples of them. What are some good examples of these Design Patterns in Java's core libraries?
推荐答案
You can find an overview of a lot of design patterns in Wikipedia. It also mentions which patterns are mentioned by GoF. I'll sum them up here and try to assign as many pattern implementations as possible, found in both the Java SE and Java EE APIs.
Creational patterns
Abstract factory (recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)
- 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 on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
- javax.swing.GroupLayout.Group#addComponent()
- All implementations of java.lang.Appendable
- java.util.stream.Stream.Builder
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)
- java.util.EnumSet#of()
- javax.xml.bind.JAXBContext#createMarshaller() and other similar methods
Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)
- java.lang.Object#clone() (the class has to implement java.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.util.Collections#list()
- java.util.Collections#enumeration()
- java.io.InputStreamReader(InputStream) (returns a Reader)
- java.io.OutputStreamWriter(OutputStream) (returns a Writer)
- 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. The java.util.Collections#newSetFromMap() and singletonXXX() 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 and Writer have a constructor taking an instance of same type.
- java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
- javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper
- javax.swing.JScrollPane
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 types LifeCycle, 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 uses ServletContext, HttpSession, HttpServletRequest, HttpServletResponse, etc.
Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)
- java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short, Long and BigDecimal)
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.*
- javax.ejb.EJB (explanation here)
- javax.inject.Inject (explanation here)
- javax.persistence.PersistenceContext
Behavioral patterns
Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in another 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 also java.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)
- java.util.Timer (all scheduleXXX() methods)
- java.util.concurrent.Executor#execute()
- java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
- java.util.concurrent.ScheduledExecutorService (all scheduleXXX() 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 a long 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)
- javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, 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 others Collections#sort().
- javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse 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 defined by an abstract type)
- All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
- All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
- javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them.