Template Method Pattern

It defines steps of an algorithm and lets sub-classes decide which steps to override.

In core java, java.util.Comparable interface is based on this pattern. Here sorting algorithm is already defined in Arrays class and steps in sort algorithm (compareTo()) is left to the user defined class(Duck.java).

public class Duck implements Comparable {
        String name;
        int weight;
	public Duck(String name, int weight) {
		this.name = name;
		this.weight = weight;
	}
	public String toString() {
		return name + " weighs " + weight;
	}
	public int compareTo(Object object) {
		Duck otherDuck = (Duck)object;
		if (this.weight < otherDuck.weight) {
			return -1;
		} else if (this.weight == otherDuck.weight) {
			return 0;
		} else { // this.weight > otherDuck.weight
			return 1;
		}
	}
}

// client to sort instances of Duck class
public class DuckSortTestDrive {
	public static void main(String[] args) {
		Duck[] ducks = {        new Duck("Daffy", 8),
		new Duck("Dewey", 2),
		new Duck("Howard", 7),
		new Duck("Louie", 2),
		new Duck("Donald", 10),
		new Duck("Huey", 2)};

		System.out.println("Before sorting:");
		display(ducks);
		
		// sort
		Arrays.sort(ducks);
		
		System.out.println("\nAfter sorting:");
		display(ducks);
	}

	public static void display(Duck[] ducks) {
		for (int i = 0; i < ducks.length; i++) {
			System.out.println(ducks<em>);
		}
	}
}

Dependency Inversion Principle and Abstract factory Pattern

DI Principle says high level components/classes should not directly depend on low level components/classes instead both should depend on the abstraction.

direct dependency Object tree
FactoryWithDependencyInversion

Object tree through abstraction
TemplatePattern
From these figures the object tree has been reversed which is dictated by DI principle.

Guidelines that help us avoid violation of DI principle:

  • No variable should hold a reference to the concrete class
  • No class should derive from concrete class
  • No method should override an implemented method of any of its subclasses

Abstract factory patterns is an extension to the factory pattern which helps in creating families of related or dependent objects without specifying their concrete classes.

Classification of design patterns and KISS principle

Classification based on creation/structure/behavior.

Creational Patterns provide us a way to decouple the client from the objects that it needs to instantiate.

  • Singleton
  • Factory
  • Abstract factory
  • Prototype
  • Builder

Structural patterns help us to compose classes or objects into larger structures

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

Behavioral Patterns dictates how classes and objects interact with each other and distribute the responsibilities

  • Template Method
  • Strategy
  • Observer
  • Command
  • Iterator
  • Chain of responsibility
  • Visitor, Mediator and Interpretor
  • State

Secondary classification based on classes and objects.

Class patterns describe how relationships between classes is defined via inheritance and these relationships are established at compile time

  • Template Method
  • Factory Method
  • Adapter
  • Interpretor

Object patterns describe relationships between objects via composition and these relationships are created at runtime which is more dynamic and flexible

  • Singleton
  • Abstract Factory
  • Composite
  • Decorator
  • Command
  • Observer
  • Strategy
  • … all others go here

It doesnt matter how any patterns we know, always make sure to keep the code simple. KISS PRINCIPLE keep it simple stupid principle

design patterns used in core java (j2se) source code

These are some of the design patterns used in core java API that I have gone through in my experience:

Decorator and Bridge patterns – java.io

Observer pattern is available as standard API

Iterator Pattern – All collection classes

Template Pattern – Arrays.sort() and Collection.sort()

Singleton Pattern – Runtime, Calendar

Factory Pattern – Wrappers of primitive data type’s valueOf methods [Integer.valueOf()]

Other most commonly used patterns:
Decorator: Java IO
Strategy Pattern: If you’ve ever used dependency injection, you’ve used the strategy pattern.
Facade: Any service APIs implement this pattern.
Singleton: Used in caching
Builder: While Writing Unit Tests
Prototype: Cloning
Adapter: asList , toString
Chain Of Responsibility: Logging
Factory: Action Mapping
MVC: Web frameworks
Proxy: Web services
Template

difference between design pattern and framework

Framework is a skeleton of code for developing java applications. Design pattern is a solution for a particular problem. The relationship is ‘Framework is made using one or more design patterns’

For example: Struts and Spring are frameworks developed by making use of MVC pattern.

core design principles

 

 MUST REMEMBER 4 ALL PROGRAMMERS 

– Encapsulate what varies

– Favor composition over inheritance

– Program to an interface, not implementations

– Strive for loosely coupled designs between objects that interact (Observer)

– Classes should be open for extension and closed for modification (Decorator)

– Dependency Inversion Principle: Depend on abstraction. Do not depend on concrete classes. This principle suggests that our high level components should not depend on low level components instead both should depend on abstractions. (Command Pattern)

– Principle of least knowledge: Only talk to your friends (Façade Pattern)

– Hollywood Principle: Don’t call us, we will call you. (Template, Factory Method, Observer Patterns)

– A class should have only one reason to change (Iterator Pattern, State Pattern)

core design pattern definitions

must for a programmer or designer

Strategy Pattern
This pattern lets you define a family of algorithms, encapsulate each one and makes them interchangeable
Favor composition over inheritance.

Observer Pattern
It defines one to many dependency between the objects so that when one object changes its state, all its dependents are notified and updated automatically

Decorator Pattern
It attaches additional responsibilities to an object dynamically at runtime. Decorators provide flexible alternative to sub-classing for extending functionality.
Note: Decorators should implement the same interface or abstract class as that of the component they are going to decorate.

Factory Method Pattern
It defines an interface for creating and object and lets subclasses decide which class to instantiate. Few guide lines to follow this pattern:
– No variable should hold a reference to the concrete class
– No class should be derived from concrete class
– No method should over-ride and implemented method of the base class

Singleton Pattern
Ensure a class has only one instance and provide a global point of access to it.

Command Pattern
It allows you to decouple the requestor of an action from the object that actually performs an action.

Adapter Pattern
It converts interface of a class into another interface the clients expect. It lets the classes work together that wouldn’t be otherwise possible because of incompatible interfaces.

Iterator Pattern
It provides a way to access the elements of an aggregate object sequentially without exposing its underlying implementation. It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface.

Composite Pattern
It helps us to compose objects into tree structures to represent part whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Façade Pattern
It provides a unified interface to a set of interfaces in a sub system. Façade defines high level interface that makes the subsystem easier to use.
Note: Actually speaking one should invoke methods that belong to:

  1. Object itself
  2. Objects passed in as a parameter to the method
  3. Any object the method instantiates
  4. Any components of the object (other object references)

Note: Adaptors and Facades may wrap multiple classes but façade’s intent is to simplify while adaptor’s is to convert the interface to something different

Template Pattern
It defines steps of an algorithm and allow subclasses to provide implementation for one or more steps.
Note: It is a great design tool for creating frameworks where framework controls how something gets done but leaves you to specify what is actually happening at each step of an algorithm. Eg: Array.sort(Obj) imples that Obj should impl Comparable interface.

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

Proxy Pattern
It provides and place holder for another object to control access to it.

All possible ways of implementing singleton pattern and its pros and cons

Here 5 possible ways are discussed
#1

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static Singleton getInstance() {
 if(instance == null) {
 instance = new Singleton();
 }
 return instance;
 }
}

Cons:
Will not suffice for multi threaded environment

#2

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static synchronized Singleton getInstance() {
 if(instance == null) {
 instance = new Singleton();
 }
 return instance;
 }
}

pros:
Will work in single and multithreaded env’s
Cons:
Will be uneccessary overhead once after instance is created for the first time because every time we call getInstance() method we need to acquire lock and release lock which is overhead after instance is available

#3

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static Singleton getInstance() {
 synchronized(this) {
 if(instance == null) {
 instance = new Singleton();
 }
 }
 return instance;
 }
}

pros:
Will not suffice in multithreaded env’s
Cons:
1. Will be uneccessary overhead once after instance is created for the first time because every time we call getInstance() method we need to acquire lock and release lock which is overhead after instance is available
2. There is a chance of more than one thread getting into if(instance == null) block there by creating multiple instances.

#4 (Double Checking)

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static Singleton getInstance() {
 if(instance == null) {
 synchronized(this) {
 if(instance == null) {
 instance = new Singleton();
 }
 }
 }
 return instance;
 }
}

pros:
Will work in multithreaded env’s
Cons:
1. It will not work in prior versions of JDK5.0
2. Double checking is verey pathetic way of implementing Singleton pattern and best practices doesnt suggest to go for this implementation.

#5

public class Singleton {
 private static Singleton instance = new Singleton();

private Singleton() {
 }

public static Singleton getInstance() {
 return instance;
 }
}

pros:
1. Simplest and trusted way as we are leaving the instantiation to the JVM
2. Works in both single and multithreaded env’s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: