Examples of GoF Design Patterns in Java's core libraries
I listed out some good examples of these Design Patterns in Java's core libraries.
Creational patterns
- Creational patterns involve object instantiation and all provide a way to decouple a client from the objects it needs to instantiate.
 
- This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.
 
Abstract factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
javax.xml.parsers.DocumentBuilderFactory#newInstance()javax.xml.transform.TransformerFactory#newInstance()javax.xml.xpath.XPathFactory#newInstance()
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
java.lang.StringBuilder#append()(unsynchronized)java.lang.StringBuffer#append()(synchronized)java.nio.ByteBuffer#put()(also onCharBuffer,ShortBuffer,IntBuffer,LongBuffer,FloatBufferandDoubleBuffer)javax.swing.GroupLayout.Group#addComponent()- All implementations of 
java.lang.Appendable 
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.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
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
java.lang.Object#clone()(the class has to implementjava.lang.Cloneable)
Singleton
Ensure a class only has one instance, and provide a global point of access to it.
Structural patterns
Structural pattern let's compose classes and objects into larger structures.
Adapter
Convert the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
java.util.Arrays#asList()java.util.Collections#list()java.util.Collections#enumeration()java.io.InputStreamReader(InputStream)(returns aReader)java.io.OutputStreamWriter(OutputStream)(returns aWriter)javax.xml.bind.annotation.adapters.XmlAdapter#marshal()and#unmarshal()
Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
- 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 usesthem. Thejava.util.Collections#newSetFromMap()andsingletonXXX()methods however comes close. 
Composite
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
java.awt.Container#add(Component)(practically all over Swing thus)javax.faces.component.UIComponent#getChildren()(practically all over JSF UI thus)
Decorator
- All subclasses of 
java.io.InputStream,OutputStream,ReaderandWriterhave a constructor taking an instance of the same type. java.util.Collections, thecheckedXXX(),synchronizedXXX()andunmodifiableXXX()methods.javax.servlet.http.HttpServletRequestWrapperandHttpServletResponseWrapper
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.
javax.faces.context.FacesContext, it internally uses among others the abstract/interface typesLifeCycle,ViewHandler,NavigationHandlerand 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
Use sharing to support large numbers of fine-grained objects efficiently.
java.lang.Integer#valueOf(int)(also onBoolean,Byte,Character,Short,LongandBigDecimal)
Proxy
Provide a surrogate or placeholder for another object to control access to it.
java.lang.reflect.Proxyjava.rmi.*javax.ejb.EJB(explanation here)javax.inject.Inject(explanation here)javax.persistence.PersistenceContext
Behavioral patterns
- Behavioral pattern is concerned with how classes and objects interact and distribute responsibility.
 
- These design patterns are all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects
 
Chain of responsibility
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.
Command
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
- All implementations of 
java.lang.Runnable - All implementations of 
javax.swing.Action 
Interpreter
java.util.Patternjava.text.Normalizer- All subclasses of 
java.text.Format - All subclasses of 
javax.el.ELResolver 
Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
- All implementations of 
java.util.Iterator(thus among others alsojava.util.Scanner!). - All implementations of 
java.util.Enumeration 
Mediator
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
java.util.Date(the setter methods do that,Dateis internally represented by alongvalue)- All implementations of 
java.io.Serializable - All implementations of 
javax.faces.component.StateHolder 
Observer
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.HttpSessionBindingListenerjavax.servlet.http.HttpSessionAttributeListenerjavax.faces.event.PhaseListener
State
Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class.
javax.faces.lifecycle.LifeCycle#execute()(controlled byFacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
java.util.Comparator#compare(), executed by among othersCollections#sort().javax.servlet.http.HttpServlet, theservice()and alldoXXX()methods takeHttpServletRequestandHttpServletResponseand the implementor has to process them (and not to get hold of them as instance variables!).javax.servlet.Filter#doFilter()
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.
- All non-abstract methods of 
java.io.InputStream,java.io.OutputStream,java.io.Readerandjava.io.Writer. - All non-abstract methods of 
java.util.AbstractList,java.util.AbstractSetandjava.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
javax.lang.model.element.AnnotationValueandAnnotationValueVisitorjavax.lang.model.element.ElementandElementVisitorjavax.lang.model.type.TypeMirrorandTypeVisitorjava.nio.file.FileVisitorandSimpleFileVisitorjavax.faces.component.visit.VisitContextandVisitCallback
Comments
Post a Comment