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.
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 -
- Creational Design patterns
- Structural Design Patterns
- Behavioral Design Patterns
- Template Method Pattern
- Mediator Pattern
- Chain of Responsibility Pattern
- Observer Pattern
- Strategy Pattern
- Command Pattern
- State Pattern
- Visitor Pattern
- Iterator Pattern
- Memento Pattern
We will see each of them in details in coming tutorials.
Places where design patterns are used in JavaSingleton 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