Monday, December 29, 2014

Iterator Pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Once you have a uniform way of accessing the elements of your aggregate (collection) objects, you can write polymorphic code that works with any of these aggregates.

The other important impact on your design is that the Iterator Pattern takes the responsibility of traversing elements and gives that responsibility to Iterator object, and not the aggregate object. This keeps the aggregate interface and implementation simpler. It removes the responsibility for iteration from the aggregate and keeps the aggregate focused on the things it should be focused on.

The core principle behind this pattern is Single Responsibility Principle, which states that "A class should have only one reason to change".

Every responsibility of a class is an area of potential change. More than one responsibility means more than one area of change. So this principle guides us to keep each class to a single responsibility.

Java language provides the iterator interface (java.util.iterator) and all collection objects in Java already implement this interface.

Saturday, December 27, 2014

State Pattern

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

This design pattern should be considered when the application needs to maintain certain state machine.

The State Pattern suggests that:
  1. Encapsulate each state into a separate class.
  2. The Context delegates to the current state to handle requests.
  3. Once a request is handled, the current state may change.
Design Principles follows:
  1. Encapsulate what varies.
  2. Favor composition over inheritance.
  3. Open-Closed principle: closed for modification but open for extension.
State and Strategy patterns are similar in structure, but what they intent to do is quite different.

In case of Strategy Pattern, objects stick to one particular kind of a behavior.

In case of State Pattern, objects change state over time according to some well defined state transitions.

Vending machine implementation is a very good application of a State Pattern.

Thursday, December 25, 2014

Decorator Pattern

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorator provides a flexible alternative to sub-classing for extending functionality.

There are two important parts to the Decorator Pattern:
  1. Components
  2. Decorators
There will be one abstract class for the components and all Concrete Components will extend this abstract component class. Also there will be one abstract Decorator class which extents the abstract component class. All concrete decorators will extent abstract Decorator class.

Design Principle: "Class should be open for extension but closed for modification".

This principle is called open-closed principle. This is one of the most important design principles.

Java IO libraries are implemented using Decorator Pattern.

Wednesday, December 24, 2014

Observer Pattern

The Observer Pattern defines one-to-many relationship between objects so that when object changes state, all of its dependents are notified and updated automatically.

Observer Pattern fits in a scenario, where there is one Subject (object) and many Observers (dependent object). The main idea behind this design pattern is loose coupling.

Design Principle:
"Strive for loosely coupled designs between objects that interact.".

When two objects are loosely coupled, they can interact, but have very little knowledge about each other. The Observer Pattern provides an object design where subjects and observers are loosely coupled.

Because:
  • The only thing the subject knows about an observer is that it implements certain interface.
  • New observers can be added anytime.
  • No need to modify subject to add new types of observers.
  • Subjects and Observers can be reused independently of each other.
  • Changes to either the subject or an observer will not affect other.

Applications of Observer Pattern:

1. Weather Application
2. Stock Quotes
3. Newspaper subscription

Tuesday, December 23, 2014

Strategy Pattern

Strategy Pattern suggest following design strategy:

1. Define a family of algorithms (an interface)
2. Encapsulate each one and make them interchangeable (composition)
3. The idea is to let the algorithm vary independently from clients that use it.

Principles behind Strategy Pattern:

1. Identify the aspects of your application that vary and separate them from what stays the same.
    - take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don't.

2. Program to an interface, not an implementation.
    - "program to an interface" really means "program to a supertype".

3. Favor composition over inheritance.
    - this allows you to change behavior at runtime as long as the object you are composing with implements the correct behavior interface.

What problems are solved by Strategy Pattern?

1. Changing Code in sub-classes
2. Duplicate Code

Monday, December 15, 2014

Singleton Pattern

Problem:

What if you want only one Object of a class? What if there is a need to have only one Object?

Solution:

The answer is "use Singleton design pattern".

So what does Singleton design pattern suggests:
  • Ensure that a class has only one instance
  • Provide a global access point to it

Implementation:
  1. Create a class
  2. Create a constructor and mark it private [so that no one else can create an instance of this class]
  3. Create a private static member variable in this class [and initialize it with null value]
  4. Create a new static method which provides way to create an instance of this class, first thing to do in this method is to make sure that there is no instance of this class created already, if not, create a new instance, store its reference in a member variable and return a reference to this instance otherwise return a previously created reference.

Java Code:

// Lazy instantiation example (called classic singleton)
public class TheSingleton {

    private static TheSingleton singleton = null;

    // restrict the instantiation by using private constructor
    private TheSingleton() {}

    // way to create an instance (only way)
    public static TheSingleton getInstance() {
        if ( singleton == null ) {
            singleton = new TheSingleton();
        }
        return singleton;
    }

    public doSomething() {
         // ....
    }

}

Above implementation is not thread-safe.

Here is thread-safe implementation using "eager instantiation" approach. Instance is created by JVM as soon as the class is loaded.

// Eager instantiation example (thread-safe)
public class TheSingleton {

    private static TheSingleton singleton = new TheSingleton();

    // restrict the instantiation by using private constructor
    private TheSingleton() {}

    // global access point
    public static TheSingleton getInstance() {
        return singleton;
    }

    public doSomething() {
         // ....
    }

}

Note: Another approach to make a Lazy singleton implementation thread-safe is to declare a getInstance method with synchronized keyword. But there is a downside to it, that is synchronization is expensive (because every call to the method is synchronized)!

Applications of Singleton Design Pattern:

  • Logging 
  • Connection pools
  • Thread pools
  • Registry object
  • Printer object
  • Device object
  • UI dialog

Sunday, December 14, 2014

What is a Design Pattern?

Design Pattern is a proven approach (well tested solution) or a guideline to structure your code.

Design Pattern is not an algorithm, but it is a best practice (suggestion) for a common type of a problem.

There are total 23 design patterns originally described in a book "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma and others (commonly referred as "Gang of Four").

Design Patterns are mainly divided into 3 categories:

1. Creational Patterns: approaches that deal with the creation of objects. It emphasizes on the flexibility of object creation.

2. Structural Patterns: These patterns suggest the best ways for creating classes and their relationship with each other.

3. Behavioral Patterns: These patterns provide guidelines for implementing the communication strategy between various objects.

Need for Design Patterns?

Primarily to deal with the change. Changes are common in software life-cycle.

e.g. You need to add new feature, changes to client specifications, you found a critical bug etc ...

And this requires restructuring of the code. It is very hard to anticipate all the problems/changes that could occur in the software ahead of the time. Fortunately, others (smart folks) have been through a lot of experience in software development and they have bundled all that knowledge into "Design Patterns". You can use those guidelines to design your software to avoid most common problems. Design Patterns minimize the impact of the change in your code and helps us to design robust object system which is flexible (open to modifications in the future).

Design patterns provide a shared vocabulary among the fellow developers, efficient ways of communicating the design.

Ultimately design patterns enable you to reuse the years of software development experience. Design patterns save you time, trial and errors.

Formal definition of a Design Pattern is as follows:
           
           "A Design Pattern is a solution to a problem in a context."

Context: The situation in which a pattern applies.
Problem: The goal you are trying to achieve.
Solution: A design that resolves the problem.