What is design pattern
Design Patterns are proven, reusable solutions to common problems that occur while designing software systems .
A Design Pattern is:
- A standard way to solve a frequently occurring software design problem.
- A guideline for structuring classes and objects.
- A method to improve code reusability, readability, and maintainability.
Why Design Patterns Are Important
- Reduce tight coupling between classes
- Improve code flexibility
- Make systems scalable
- Follow SOLID principles
- Improve communication between developers
- Speed up development using proven solutions
Categories (Types) of Design Patterns
Design patterns are mainly divided into three major categories
1. Creational Design Patterns
Instead of creating objects directly, these patterns control how objects are created.
- Singleton
- Factory Method
- Abstract Factory Method
- Builder
- Prototype
2. Structural Design Patterns
- structural design pattern provide different ways to create a class structure , for example using Inheritance and composition to create a large object from small object .
- Structural design pattern deal with how classes and objects are arranged or composed .
- Structural Design patterns are
- Adapter
- Bridge
- Composite
- Decorator
- Facade
- Flyweight
- Proxy
3.Behavioral Design Patterns
Behavioral design pattern Focus on communication between objects. They define how objects interact and share responsibilities.
Behavioral patterns are
- Observer
- Strategy
- Command
- Iterator
- Mediator
- Memento
- State
- Template Method
- Chain of Responsibility
- Visitor
Example: Create objects from one central place.
Client does NOT know how objects are created.
1. Create Interface
interface Vehicle {
void drive();
}
2. Create Classes
class Car implements Vehicle {
public void drive() {
System.out.println("Driving Car");
}
}
class Bike implements Vehicle {
public void drive() {
System.out.println("Driving Bike");
}
}
3. Factory Class
class VehicleFactory {
public static Vehicle getVehicle(String type) {
if(type.equalsIgnoreCase("car"))
return new Car();
else if(type.equalsIgnoreCase("bike"))
return new Bike();
return null;
}
}
4.Client Code
public class Main {
public static void main(String[] args) {
Vehicle v = VehicleFactory.getVehicle("car");
v.drive();
}
}