Design Patterns in Java (JDK) and Java Frameworks
Recently I was reading up on Design Patterns & Java to refresh my knowledge and was pleasantly surprised to see a pretty large number of patterns used in the JDK(Java SDK or rather the Java standard library) and Java Frameworks such as Hibernate and Spring. I have seen this in STL among others to a lesser degree.
Here are some, in no particular order:
The links are to Wikipedia Design Pattern pages which I liked over the Portland pattern repository for overview:
- Factory pattern: Any method which creates an objects, initializes it and returns it. socket.getInputStream(), Executors.newFixedThreadPool(), Collections.singleton(), etc
- Iterator pattern: Used to traverse collections. Collection.getIterator()
- Decorator pattern: Use to wrap\convert Streams adding functionality to them. Not Adapter pattern due to added functionality. Wrap a FileInputStream into a Reader and use .readLine() to read lines.
- Chain-of-responsibility pattern: The streams as above, the Streams chained handle the request and pass it after operating on it. Criteria, an alternative to HQL in Hibernate.
- Strategy pattern: Concrete strategies to implement family of algorithms which are interchangeable. All collections are strategies, accessible using a common interface, depending what what is stored, Map interface can be HashMap, TreeMap, LinkedHashMap
- Template method pattern: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. java.util.AbstractCollection expects iterator, size, add and provides addAll, clear, contains, containsAll, isEmpty, remove, etc.
- Singleton pattern: Java Security Manager, System.getSecurityManager(); Socket accept and other permissions
- Prototype pattern: Has a Cloneable marker interface, which indicates to Object.clone() that it is legal\safe to make a field copy. Should not be done for open files, self-allocated memory, ….
- Observer pattern: Built in support in JDK including Observer interface & Observable classes.
There are many more such as Thread pool pattern, Inversion of control which forms the basis of Spring framework and so on.
Some other posts
- Excerpt: ...
- Excerpt: ...
- Excerpt: ...
- Excerpt: ...
- Excerpt: ...
