oop used api - Examples of GoF Design Patterns in Java's core libraries
- Observer pattern throughout whole swing (
- MVC also in swing
- Adapter pattern: InputStreamReader and OutputStreamWriter
MouseAdapterare not adapters; they are actually Null Objects. Poor naming choice by Sun.
- Decorator pattern (
BufferedInputStreamcan decorate other streams such as
- AbstractFactory Pattern for the AWT Toolkit and the Swing pluggable look-and-feel classes
ButtonGroupfor Mediator pattern
AbstractActionmay be used for different visual representations to execute same code -> Command pattern
- Interned Strings or CellRender in JTable for Flyweight Pattern (Also think about various pools - Thread pools, connection pools, EJB object pools - Flyweight is really about management of shared resources)
- The Java 1.0 event model is an example of Chain of Responsibility, as are Servlet Filters.
- Iterator pattern in Collections Framework
- Nested containers in AWT/Swing use the Composite pattern
- Layout Managers in AWT/Swing are an example of Strategy
and many more I guess
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?
RMI is based on Proxy.
Should be possible to cite one for most of the 23 patterns in GoF:
- Abstract Factory: java.sql interfaces all get their concrete implementations from JDBC JAR when driver is registered.
- Builder: java.lang.StringBuilder.
- Factory Method: XML factories, among others.
- Prototype: Maybe clone(), but I'm not sure I'm buying that.
- Singleton: java.lang.System
- Adapter: Adapter classes in java.awt.event, e.g., WindowAdapter.
- Bridge: Collection classes in java.util. List implemented by ArrayList.
- Composite: java.awt. java.awt.Component + java.awt.Container
- Decorator: All over the java.io package.
- Facade: ExternalContext behaves as a facade for performing cookie, session scope and similar operations.
- Flyweight: Integer, Character, etc.
- Proxy: java.rmi package
- Chain of Responsibility: Servlet filters
- Command: Swing menu items
- Interpreter: No directly in JDK, but JavaCC certainly uses this.
- Iterator: java.util.Iterator interface; can't be clearer than that.
- Mediator: JMS?
- Observer: java.util.Observer/Observable (badly done, though)
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.
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.