Prototype Pattern

Definition

Cloning an object by reducing the cost of creation.

Where to use & benefits

  • When there are many subclasses that differ only in the kind of objects,
  • A system needs independent of how its objects are created, composed, and represented.
  • Dynamic binding or loading a method.
  • Use one instance to finish job just by changing its state or parameters.
  • Add and remove objects at runtime.
  • Specify new objects by changing its structure.
  • Configure an application with classes dynamically.

The prototype pattern is a creational design pattern. In the prototype pattern, a new object is created by cloning an existing object. In JavaSW, the clone() method is an implementation of this design pattern. The prototype pattern can be a useful way of creating copies of objects. One example of how this can be useful is if an original object is created with a resource such as a data stream that may not be available at the time that a clone of the object is needed. Another example is if the original object creation involves a significant time commitment, such as reading data from a databaseW or over a network. An added benefit of the prototype pattern is that it can reduce class proliferation in a project by avoiding factory proliferation.

 

Advertisements

Builder Pattern

Definition

Construct a complex object from simple objects step by step.

Where to use & benefits

  • Make a complex object by specifying only its type and content. The built object is shielded from the details of its construction.
  • Want to decouple the process of building a complex object from the parts that make up the object.
  • Isolate code for construction and representation.
  • Give you finer control over the construction process.

The builder pattern is a creational design pattern used to assemble complex objects. With the builder pattern, the same object construction process can be used to create different objects. The builder has 4 main parts: a Builder, Concrete Builders, a Director, and a Product.

A Builder is an interface (or abstract class) that is implemented (or extended) by Concrete Builders. The Builder interface sets forth the actions (methods) involved in assembling a Product object. It also has a method for retrieving the Product object (ie, getProduct()). The Product object is the object that gets assembled in the builder pattern.

Concrete Builders implement the Builder interface (or extend the Builder abstract class). A Concrete Builder is responsible for creating and assembling a Product object. Different Concrete Builders create and assemble Product objects differently.

A Director object is responsible for constructing a Product. It does this via the Builder interface to a Concrete Builder. It constructs a Product via the various Builder methods.

There are various uses of the builder pattern. For one, if we’d like the construction process to remain the same but we’d like to create a different type of Product, we can create a new Concrete Builder and pass this to the same Director. If we’d like to alter the construction process, we can modify the Director to use a different construction process.

 

 

Singleton Pattern

Definition

One instance of a class or one value accessible globally in an application.

Where to use & benefits

  • Ensure unique instance by defining class final to prevent cloning.
  • May be extensible by the subclass by defining subclass final.
  • Make a method or a variable public or/and static.
  • Access to the instance by the way you provided.
  • Well control the instantiation of a class.
  • Define one value shared by all instances by making it static.

A singleton is a class that is instantiated only once. This is typically accomplished by creating a static field in the class representing the class. A static method exists on the class to obtain the instance of the class and is typically named something such as getInstance(). The creation of the object referenced by the static field can be done either when the class is initialized or the first time that getInstance() is called. The singleton class typically has a private constructor to prevent the singleton class from being instantiated via a constructor. Rather, the instance of the singleton is obtained via the static getInstance() method.

The SingletonExample class is an example of a typical singleton class. It contains a private static SingletonExample field. It has a private constructor so that the class can’t be instantiated by outside classes. It has a public static getInstance() method that returns the one and only SingletonExample instance. If this instance doesn’t already exist, the getInstance() method creates it. The SingletonExample class has a public sayHello() method that can be used to test the singleton.

SingletonExample.java

package com.cakes;

public class SingletonExample {

	private static SingletonExample singletonExample = null;

	private SingletonExample() {
	}

	public static SingletonExample getInstance() {
		if (singletonExample == null) {
			singletonExample = new SingletonExample();
		}
		return singletonExample;
	}

	public void sayHello() {
		System.out.println("Hello");
	}
}

The Demo class obtains a SingletonExample singleton class via the call to the static SingletonExample.getInstance(). We call the sayHello() method on the singleton class. Executing the Demo class outputs “Hello” to standard output.

Demo.java

package com.cakes;

public class Demo {

	public static void main(String[] args) {
		SingletonExample singletonExample = SingletonExample.getInstance();

		singletonExample.sayHello();
	}

}

Singleton classes are a useful way of concentrating access to particular resources into a single class instance. 🙂

Abstract Factory Pattern

Definition

Provides one level of interface higher than the factory pattern. It is used to return one of several factories.

Where to use & benefits

  • Creates families of related or dependent objects like Kit.
  • Provides a class library of products, exposing interface not implementation.
  • Needs to isolate concrete classes from their super classes.
  • A system needs independent of how its products are created, composed, and represented.
  • Try to enforce a constraint.
  • An alternative to Facade to hide platform-specific classes
  • Easily extensible to a system or a family

 

Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.

There is also a view that abstract factory is ‘also’ implemented using prototype instead of factory methords pattern. Beginners for now please don’t yourself with that. Just go with factory methods pattern.

As there is a word ‘abstract’ in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is from object oriented programming paradim.

Sample abstract factory design pattern implementation in Java API

XML API implements abstract factory. There is a class name SchemaFactory. This acts as a factory and supports implemenation of multiple schemas using abstract factory design pattern.

Sample Java Source Code for Factory Method Design Pattern

Following is the interface, that will be returned as the final end product from the factories.


package com.javapapers.sample.designpattern.abstractfactory;

public interface Animal {
 public void breathe();
}

Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.


package com.javapapers.sample.designpattern.abstractfactory;

public interface AnimalFactory {
 public Animal createAnimal();
}

One of the factory from a predefined set which will instantiate the above interface.


package com.javapapers.sample.designpattern.abstractfactory;

public class SeaFactory implements AnimalFactory {

 public Animal createAnimal() {
 return new Shark();
 }

}

Second factory from a predefined set which will instantiate the Animal interface.


package com.javapapers.sample.designpattern.abstractfactory;

public class LandFactory implements AnimalFactory {
 public Animal createAnimal() {
 return new Elephant();
 }
}

Implementation of an Animal. This class is grouped with the first abstract factory.


package com.javapapers.sample.designpattern.abstractfactory;

public class Shark implements Animal {
 public void breathe() {
 System.out.println("I breathe in water! He he!");
 }
}

Implementation of an Animal. This class is grouped with the second abstract factory.


package com.javapapers.sample.designpattern.abstractfactory;

public class Elephant implements Animal {
 public void breathe() {
 System.out.println("I breathe with my lungs. Its easy!");
 }
}

Following class consumes the abstract factory.


package com.javapapers.sample.designpattern.abstractfactory;

public class Wonderland {
 public Wonderland(AnimalFactory factory) {
 Animal animal = factory.createAnimal();
 animal.breathe();
 }
}

Testing the abstract factory design pattern.


package com.javapapers.sample.designpattern.abstractfactory;

public class SampleAbstractFactory {

 public static void main(String args[]){
 new Wonderland(createAnimalFactory("water"));
 }

 public static AnimalFactory createAnimalFactory(String type){
 if("water".equals(type))
 return new SeaFactory();
 else
 return new LandFactory();
 }
}

Output of the above sample program for abstract factory pattern


<code>I breathe in water! He he!</code>

Factory Method Pattern

Definition

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.

Where to use & benefits

  • Connect parallel class hierarchies.
  • A class wants its subclasses to specify the object.
  • A class cannot anticipate its subclasses, which must be created.
  • A family of objects needs to be separated by using shared interface.
  • The code needs to deal with interface, not implemented classes.
  • Hide concrete classes from the client.
  • Factory methods can be parameterized.
  • The returned object may be either abstract or concrete object.
  • Providing hooks for subclasses is more flexible than creating objects directly.
  • Follow naming conventions to help other developers to recognize the code structure.

 

A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.

Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Sample factory method design pattern implementation in Java API

For a reference of how the factory method design pattern is implemented in Java, you can have a look at SAXParserFactory. It is a factory class which can be used to intantiate SAX based parsers to pares XML. The method newInstance is the factory method which instantiates the sax parsers based on some predefined logic.

Block diagram for The Design Pattern

Sample Java Source Code for Factory Method Design Pattern

Based on comments received from users, I try to keep my sample java source code as simple as possible for a novice to understand.

Base class:


package com.javapapers.sample.designpattern.factorymethod;

//super class that serves as type to be instantiated for factory method pattern
public interface Pet {

 public String speak();

}

First subclass:


package com.javapapers.sample.designpattern.factorymethod;

//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {

 public String speak() {
 return "Bark bark...";
 }
}

Second subclass:


package com.javapapers.sample.designpattern.factorymethod;

//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
 public String speak() {
 return "Quack quack...";
 }
}

Factory class:


package com.javapapers.sample.designpattern.factorymethod;

//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {

 public Pet getPet(String petType) {
 Pet pet = null;

 // based on logic factory instantiates an object
 if ("bark".equals(petType))
 pet = new Dog();
 else if ("quack".equals(petType))
 pet = new Duck();
 return pet;
 }
}

Using the factory method to instantiate


package com.javapapers.sample.designpattern.factorymethod;

//using the factory method pattern
public class SampleFactoryMethod {

 public static void main(String args[]){

 //creating the factory
 PetFactory petFactory = new PetFactory();

 //factory instantiates an object
 Pet pet = petFactory.getPet("bark");

 //you don't know which object factory created
 System.out.println(pet.speak());
 }

}

Output of the above sample program for Factory Method Pattern


<code>Bark bark</code>

Introduction To Design Patterns

Pattern is a defined, used and tested solution for a know problem. Design patterns is all about re-use. Software design patterns evolved as a subject of study only when object oriented programming started becoming popular. OOPS and design patterns became inseparable.

In OOPS, we should have well defined boundaries for objects. That is every object should have its roles and responsibilities well defined. Then at next level, we should have a clear interaction plan between objects. If you design a OO software with the above principle, then by default you will be following some of the already defined design patterns.

A formal definition for design patterns, “A design pattern addresses a recurring design problem that arises in specific design situations and presents a solution to it” (Buschmann, et. al. 1996)

Java widely uses design patterns in its APIs. It started as early as Java 1.2 in java foundation classes. By then you can see the widespread use of commonly know design patterns in collections framework and IO packages. When I say commonly known design patterns, I mention about the set of 23 design patterns by Gang of Four (GOF). Gamma, Helm, Johnson and Vlissides known as Gang of Four (GOF) published a book “Design Patterns — Elements of Reusable Software” (1995) based on their series of technical meetings. It is one of the best seller in computer science books till date.

In China gang of four means different set of people. Jiang Qing (Mao Zedong’s fourth wife), Zhang Chunqiao, Yao Wenyuan, and Wang Hongwen were very popular leaders of cultural revolution. They almost seized power after Mao Zedong’s death. But they were finally arrested and imprisoned for life.

Our GOF divided the 23 design patterns into three types creational design patterns, structural design patterns and behavioral design patterns.

Creational design patterns can be used to instantiate objects. Instead of instantiating objects directly, depending on scenario either X or Y object can be instantiated. This will give flexibility for instantiation in high complex business logic situations.

Structural design patterns can be used to organize your program into groups. This segregation will provide you clarity and will enable you for easier maintainability.

  • Adapter Pattern
  • Bridge Pattern
  • Composite Pattern
  • Decorator Pattern
  • Facade Pattern
  • Flyweight Pattern
  • Proxy Pattern

Behavioral design patterns can be used to define the communication and control flow between objects.

  • Chain Of Responsibility Pattern
  • Command Pattern
  • Interpreter Pattern
  • Iterator Pattern
  • Mediator Pattern
  • Memento Pattern
  • Observer Pattern
  • State Pattern
  • Strategy Pattern
  • Template Method Pattern
  • Visitor Pattern

Reference Book : Design Pattern Book