Friday, 22 March 2013

Introduction to Design Patterns

What are design patterns?

        Programmers usually face some common problems while designing and formulating their programs. Various such problems patterns are identified and their solution is documented which we call design patterns.
So in a nutshell Design Patterns are best practices how to solve common know problems.

Understanding a bit more.

     Let us try to understand these design patterns by considering one such design problem.

     Single printer in a company

      Lets say we have a single printer in the entire company and we have an associated service class which provides printer service to every employee who wishes to print something. Now what sub goals do you have while designing such a service class. You have only one printer and hence you need only one instance of this service class. To achieve this goal you would design your class is such a way that at all time you can have only one instance of the service class. This design pattern is commonly know as Singleton Design pattern. We will look into it in more details but i guess this example will suffice in achieving our goal to understand what these design patterns are all about.

   Another example would be your logging class. You want only one instance of logger to be used. So you would prefer using Singleton Pattern.

Important principles in OO Design 

  • Code for interface not implementation.
  • Prefer composition over inheritance.
  • Interacting Objects should be loosely couple.
  • For each class design aim for low coupling and high cohesion.
  • Classes should be open for extension but closed for modification.
These are used in almost all design patterns and form like the basic guidelines. So do keep these in mind. We will use them while discussing about design patterns in detail.


Types of design patterns

   Design patterns are categorized into 3 types as follows - 

Places where design patterns are used in Java

Singleton pattern is used in Java.lang.Runtime , java.util.Calendar, Java.awt.Toolkit, Java.awt.Desktop classes, Factory pattern is used along with various Immutable classes likes Integer e.g. Integer.valueOf and Observer pattern which is used in Swing and many event listener frameworks.Book that I would recommend to study Design Patterns for the beginners  is -
  • "Head first Design Patterns"

Or you can refer to the book written by the Gang of Four themselves - 
  • "Design Patterns"- Elements of Reusable Object-Oriented Software

Related Posts

t> UA-39527780-1 back to top