Saturday, February 02, 2008

Prototype

Name : Prototype
Context : Obtain a copy
Consequences :
1)Add remove products at runtime
2)Specify new objects by varying value or structure
3)Reduced Subclassing
4)Configure an application with class dynamically
Examples
Anything implementing clone(),
Class

Factory method

Name : Factory Method
Context : Hide the implementation class but defer the instantiation to subclass
Consequence
a) Provides hooks for subclass
Examples
Calendar.getInstance()
Connection conn = java.sql.DriverManager.getConnection(uri, name, password);

Friday, February 01, 2008

Abstract Factory

Name : Abstract Factory
Context : Creating Related family of objects
Example: Toolkit(awt)
java.sql.Connection (sort of creates Statements and PreparedStatements and CallableStatements where each is specific to the database)
Consequence
1) Exchange Product Families
2) Supporting new kinds of products
3) Factories are normally singletons! But they need not be.
4)Note that every factory must support every type of object to be created. This is sometimes problematic.

Singleton (Creational)

Name : Singleton
Comment : Probably the best known (atleast if you go by answers you get in interviews to the question 'Patterns you have used') of the design patterns and probably one of the text book cases of people ignoring understand the context and understand the consequences when it comes to this pattern
Context : Need only 1(or a fixed or controllable number of instances) (e.g. memory consumption , or heavy initialization like reading a file,a requirement - there is only one Neo, a pre java 1.5 enum such that == can be used )
Examples : Single Instance (java.awt.Toolkit, Inspector)
Consequences :
a) Controlled access to state
b) Permits a variable number of instances (e.g. access to any object pool)!
c) Watch out for real world multiple managed servers, clusters etc(older versions of Expresso framework used an in memory primary key generator as an incremented singleton - no use in a cluster. Real world naive code that uses a timestamp plus ip address as unique key through a singleton)
d) Watch out for synchronized access for loading the singleton, thread safety, shared state.
e) Watch out for serializable (might break singletoness if you dont follow effective java)
f) Watch out for static block errors during initialization(if initialising eagerly). Will cause NoClassDefFoundErrors.
g) Watch out for being unable to reset a singleton (e.g. a singleton that reads a file and stores it.If your not careful , changing the file needs a bounce of the server)
h) Watch out for singletonitis. i.e. Making classes singleton even when there is no shared state, no performance or initialisation penalty.
i) Watch out for problems testing the singleton

With all the Watch out's is this pattern worth the trouble? read the context!

Design Patterns Course

The following series of posts deal with a design pattern course I conducted for a few colleagues of my team who insisted that I knew enough to conduct such a course(I don't). One of the problems I had faced while attending the design patterns course conducted by probably the best Technical Manager I've worked under (Homi Bharda) was that practical examples were hard to come by, where you could see the usefullness and though the Design patterns book by Erich Gamma did point to some examples they almost always dealt with GUI heavy , stateful , highly object oriented programs while at that stage I dealt with mostly stateless CRUD web based applications.
I resolved that any course I took would show practical examples and what better example than the Java API which was quite familiar to my colleagues. I also had a lot of problem differentiating between patterns. Some of the Factory patterns looked alike. Some of the patterns like Command and Strategy looked alike. I resolved to have some comparisons at least.

What these notes dont have is my bitterly cynical comments e.g. of people who code such that all their classes have a suffix which is pattern e.g. ObjectCommand uses an ObjectFacade uses an ObjectFactory creates an ObjectService which uses an ObjectDAO and returns an ObjectAdapter which wraps an ObjectDecorator which wraps a ObjectDTO (Disclaimer I have done this too). This literally is the developer's cry look Im a designer , I use patterns , I even know their names! But ask them Give me some examples of design patterns in the Java SDK and we have a) Blank Stares b) Singleton c) A very very few Decorator.
So anyway other than the above rant , very few cynical comments


General Notes
What is a pattern ?
A Name, A Recurring problem with context, A recommended Solution(or way ahead), Consequences and Alternatives
The bit a lot of people miss out is the Context and the Consequence. A pattern cannot be used irrespective of the context . This causes problems like 'Singletonitis'. A pattern always has some consequence. A pattern probably does have alternatives which are to be evaluated.
A pattern need not always be up front design, you can arrive at many patterns with a judicious use of refactoring and some simple principles notably DRY.
Patterns are also sometimes subsumed by the language or the platform (e.g. Factory in Visual Basic COM and Iterator in java) and some people refer to patterns as deficiency in the language / platform ( I dont agree!).
Anyone who does anything with Design Patterns has to refer to Erich Gamma's et al book , and thats what I have based this on including the organisation of the patterns as Creational, Behavioral and Structural. Its quite difficult for novices (like me) to differentiate what between what constitutes a behavioral or structural pattern so dont bother right now.
Also note that any Object oriented system has available to it the mechanisms of Polymorphism and Inheritance (Implementation of Interface). Therefore all diagrams of Design patterns will look similar in a lot of case. it is necessary to understand the nuance and differences and context.
And lastly in a web project , differentiate between building a framework and solving a problem at hand. Its very easy to get carried away and over engineer and its as easy to under engineer, and it's also simple to shout TDD, refactoring , agile. Ultimately experience is what you use to decide whether you need a pattern upfront or later, Refactor or not. And anyone who tells you otherwise is either a manager or a consultant.