This is part two of design patterns used in JDK where I shall try to cover some more patterns definition and their usage in JDK. You can find the First part of this series Here.
Adapter – Convert the interface of a class into another interface clients expect. / Adapter lets classes work together, that could not otherwise because of incompatible interfaces. Note that there are two types of adapter, one is class level adapter and other is object level adapter. Examples –
- java.io.InputStreamReader(InputStream) (returns a Reader)
- java.io.OutputStreamWriter(OutputStream) (returns a Writer)
- javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()
Bridge – Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Examples –
- JDBC-ODBC Bridge
Composite – Compose objects into tree structures to represent part-whole hierarchies. / Composite lets clients treat individual objects and compositions of objects uniformly. Examples –
- Includes in JSP
- java.nio.ByteBuffer#put(ByteBuffer) (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
- java.awt.Container#add(Component) (practically all over Swing thus)
A very detailed explanation about Composite pattern is Here
Decorator – add additional responsibilities dynamically to an object. Examples –
- All subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor taking an instance of same type.
- Almost all implementations of java.util.List, Set and Map have a constructor taking an instance of same type.
- java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
- javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper
- Display tag custom tag library proved option to decorator for rendering of tables in JSP.
Flyweight – use sharing to support a large number of objects that have part of their internal state in common where the other part of state can vary. Examples –
- java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short, Long, Float and Double)
- Java String creation. (Read about string creation in Java specification)
- Swing borders
Proxy – provide a “Placeholder” for an object to control references to it. If you use spring framework, you should be very well acquainted with Proxy. Examples –
- Java RMI
- Spring AOP creates proxies for supplied objects
- All libraries which use Java proxy , Reflection proxy and CGLIB proxy
Memento – capture the internal state of an object without violating encapsulation and thus providing a mean for restoring the object into initial state when needed.
- 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