views:

3459

answers:

7

I am learning GoF Java Design Patterns and I want to see some real life examples of them. Can you guys point to some good usage of these Design Patterns.(preferably in Java's core libraries).

Thank you

+12  A: 
  1. Observer pattern throughout whole swing (Observable, Observer)
  2. MVC also in swing
  3. Adapter pattern: InputStreamReader and OutputStreamWriter NOTE: ContainerAdapter, ComponentAdapter, FocusAdapter, KeyAdapter, MouseAdapter are not adapters; they are actually Null Objects. Poor naming choice by Sun.
  4. Decorator pattern (BufferedInputStream can decorate other streams such as FilterInputStream)
  5. AbstractFactory Pattern for the AWT Toolkit and the Swing pluggable look-and-feel classes
  6. java.lang.Math could be considered a kind of Singleton (final + all methods static)
  7. ButtonGroup for Mediator pattern
  8. Action, AbstractAction may be used for different visual represntations to execute same code -> Command pattern
  9. 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)
  10. The Java 1.0 event model is an example of Chain of Responsibility, as are Servlet Filters.
  11. Iterator pattern in Collections Framework
  12. Nested containers in AWT/Swing use the Composite pattern
  13. Layout Managers in AWT/Swing are an example of Strategy

and many more I guess

jitter
java.lang.Math (6th one) is not singleton, you don't have an instance to start with, everything is static. That's not singleton
Ion Todirel
+4  A: 

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.

uckelman
+1  A: 

Swing also uses the Composite Pattern

Vincent Ramdhanie
+1  A: 

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.

Esko
+3  A: 
  1. Flyweight is used with some values of Byte, Short, Integer, Long and String.
  2. Facade is used in many place but the most obvious is Scripting interfaces.
  3. Singleton - java.lang.Runtime comes to mind.
  4. Abstract Factory - Also Scripting and JDBC API.
  5. Command - TextComponent's Undo/Redo.
  6. Interpreter - RegEx (java.util.regex.) and SQL (java.sql.) API.
  7. Prototype - Not 100% sure if this count, but I thinkg clone() method can be used for this purpose.
NawaMan
You're correct about Prototype
Scott Stanchfield
+2  A: 

RMI is based on Proxy.

Should be possible to cite one for most of the 23 patterns in GoF:

  1. Abstract Factory: java.sql interfaces all get their concrete implementations from JDBC JAR when driver is registered.
  2. Builder:
  3. Factory Method: XML factories, among others.
  4. Prototype: Maybe clone(), but I'm not sure I'm buying that.
  5. Singleton: java.lang.System
  6. Adapter:
  7. Bridge:
  8. Composite:
  9. Decorator: All over the java.io package.
  10. Facade:
  11. Flyweight: Integer, Character, etc.
  12. Proxy: java.rmi package
  13. Chain of Responsibility: Servlet filters
  14. Command: Swing menu items
  15. Interpreter: No directly in JDK, but JavaCC certainly uses this.
  16. Iterator: java.util.Iterator interface; can't be clearer than that.
  17. Mediator: JMS?
  18. Memento:
  19. Observer: java.util.Observer/Observable (badly done, though)
  20. State:
  21. Strategy:
  22. Template:
  23. Visitor:

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.

duffymo
+126  A: 

You can find an overview of a lot design patterns in Wikipedia. It also mentions which patterns are mentioned by GoF. I'll sum them up here and try to assign as much as possible pattern implementations found in both the Java SE and Java EE API's.


Creational patterns

Abstract factory (recognizeable by creational methods returning an abstract/interface type)

Builder (recognizeable by creational methods returning the instance itself)

Factory method (recognizeable by creational methods returning a concrete type)

Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)

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)

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)

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type)

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)

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)

The Wikipedia example is IMHO a bit poor, lazy loading has actually completely nothing to do with the proxy pattern at all.


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)

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)

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

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)

Template method (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)

Visitor (recognizeable by two different abstract/interface types which has methods definied which takes each the other abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)

BalusC
+10 awesome answer! (too bad I can only +1)
Dave DeLong
I dont know what to say.
kunjaan
+1 Jolly Good !!!
Romain Hippeau
impressive.. :) +1. `javax.lang.model.element` defines visitors ;) I'm not quite sure whether `doXXX` and `doFilter` are "strategies".
Bozho
@Bozho: Thank you for the visitor example! (that whole API is actually new to me btw). In the `doXXX()` and `doFilter()` you basically write the strategy algorithm alone. The server loads and executes it.
BalusC
hm, yes.. my impression is that the strategies have to be objects conforming to a strategy interface, and thus interchangeable at runtime
Bozho
Very impressive indeed :o
cwap
Best post I've ever seen.
Helper Method