Factory design pattern is most suitable when complex object creation steps are involved. To ensure that these steps are centralized and not exposed to composing classes. Abstract factory pattern is used whenever we need another level of abstraction over a group of factories created using factory pattern.
There are 11 behavioral design patterns defined in the GoF design patterns. used to create a template method stub and defer some of the steps of implementation to the subclasses. used to provide a centralized communication medium between different objects in a system.
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.
javax.xml.parsers.DocumentBuilderFactory#newInstance()
javax.xml.transform.TransformerFactory#newInstance()
javax.xml.xpath.XPathFactory#newInstance()
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()
java.lang.Appendable
java.util.stream.Stream.Builder
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 methodsjava.lang.Object#clone()
(the class has to implement java.lang.Cloneable
)java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()
java.lang.System#getSecurityManager()
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()
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.java.awt.Container#add(Component)
(practically all over Swing thus)javax.faces.component.UIComponent#getChildren()
(practically all over JSF UI thus)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
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.java.lang.Integer#valueOf(int)
(also on Boolean
, Byte
, Character
, Short
, Long
and BigDecimal
)java.lang.reflect.Proxy
java.rmi.*
javax.ejb.EJB
(explanation here)javax.inject.Inject
(explanation here)javax.persistence.PersistenceContext
java.util.logging.Logger#log()
javax.servlet.Filter#doFilter()
java.lang.Runnable
javax.swing.Action
java.util.Pattern
java.text.Normalizer
java.text.Format
javax.el.ELResolver
java.util.Iterator
(thus among others also java.util.Scanner
!).java.util.Enumeration
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()
java.util.Date
(the setter methods do that, Date
is internally represented by a long
value)java.io.Serializable
javax.faces.component.StateHolder
java.util.Observer
/java.util.Observable
(rarely used in real world though)java.util.EventListener
(practically all over Swing thus)javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener
javax.faces.lifecycle.LifeCycle#execute()
(controlled by FacesServlet
, the behaviour is dependent on current phase (state) of JSF lifecycle)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()
java.io.InputStream
, java.io.OutputStream
, java.io.Reader
and java.io.Writer
.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.javax.lang.model.element.AnnotationValue
and AnnotationValueVisitor
javax.lang.model.element.Element
and ElementVisitor
javax.lang.model.type.TypeMirror
and TypeVisitor
java.nio.file.FileVisitor
and SimpleFileVisitor
javax.faces.component.visit.VisitContext
and VisitCallback
Observable
, Observer
)ContainerAdapter
, ComponentAdapter
, FocusAdapter
, KeyAdapter
, MouseAdapter
are not adapters; they are actually Null Objects. Poor naming choice by Sun.BufferedInputStream
can decorate other streams such as FilterInputStream
)java.lang.Runtime#getRuntime()
is SingletonButtonGroup
for Mediator patternAction
, AbstractAction
may be used for different visual representations to execute same code -> Command patternand many more I guess
clone()
method can be used for this purpose.RMI is based on Proxy.
Should be possible to cite one for most of the 23 patterns in GoF:
I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.
The Abstract Factory pattern is used in various places.
E.g., DatagramSocketImplFactory
, PreferencesFactory
. There are many more---search the Javadoc for interfaces which have the word "Factory" in their name.
Also there are quite a few instances of the Factory pattern, too.
Even though I'm sort of a broken clock with this one, Java XML API uses Factory a lot. I mean just look at this:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
String title = XPathFactory.newInstance().newXPath().evaluate("//title", doc);
...and so on and so forth.
Additionally various Buffers (StringBuffer, ByteBuffer, StringBuilder) use Builder.
java.util.Collection#Iterator is a good example of a Factory Method. Depending on the concrete subclass of Collection you use, it will create an Iterator implementation. Because both the Factory superclass (Collection) and the Iterator created are interfaces, it is sometimes confused with AbstractFactory. Most of the examples for AbstractFactory in the the accepted answer (BalusC) are examples of Factory, a simplified version of Factory Method, which is not part of the original GoF patterns. In Facory the Factory class hierarchy is collapsed and the factory uses other means to choose the product to be returned.
An abstract factory has multiple factory methods, each creating a different product. The products produced by one factory are intended to be used together (your printer and cartridges better be from the same (abstract) factory). As mentioned in answers above the families of AWT GUI components, differing from platform to platform, are an example of this (although its implementation differs from the structure described in Gof).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With