Design Patterns (Introduction)
Design Patterns are general, reusable solutions to common problems in software
design.
They help programmers write code that is flexible, reusable, and easy to maintain.
1. Creational Design Patterns
These patterns focus on how objects are created.
Abstract Factory
• Creates families of related objects without specifying their exact classes.
• Example: Creating different blog layouts for different themes.
• Use when: You need to create related objects together.
Builder Pattern
• Builds complex objects step by step.
• Useful when an object has many optional parts.
When to use:
• When an object has many parameters.
• To avoid large constructors.
When not to use:
• When the object is simple.
• When performance is very important.
Factory Pattern
• Provides a common interface to create objects.
• The exact object type is decided at runtime.
Usage:
• Creating user objects, database models, etc., in backend systems.
Singleton Pattern
• Ensures only one instance of a class exists.
• Provides a global access point.
Usage:
• Database connection
• Login system
• Configuration manager
2. Behavioral Design Patterns
These patterns focus on how objects communicate and interact.
Command Pattern
• Encapsulates a request as an object.
• Useful for Undo/Redo operations.
Use when:
• You need to store and replay actions.
Do not use when:
• Operations are very simple.
Iterator Pattern
• Allows you to access elements one by one without exposing internal
structure.
Example:
• Browsing a music playlist.
Usage:
• Used in standard collections like lists, maps, vectors.
Do not use when:
• Memory usage is very critical.
Mediator Pattern
• Uses a central object (mediator) to manage communication between
objects.
Example:
• Chat system where mediator handles message delivery.
Do not use when:
• Communication is already simple and decentralized.
3. Structural Design Patterns
These patterns focus on how classes and objects are combined.
Adapter Pattern
• Makes incompatible interfaces work together.
Use when:
• Reusing old classes with new interfaces.
• Integrating third-party libraries.
Do not use when:
• Performance is critical.
• Interfaces are stable and simple.
Facade Pattern
• Provides a simple interface to a complex system.
Example:
• Home theater system with one button to start everything.
• CRM system simplifying customer operations.
Use when:
• System is complex.
Do not use when:
• System is already simple.
Composite Pattern
• Treats single objects and groups of objects the same way.
• Builds a tree-like structure.
Example:
• Car → Engine → Electrical parts → Chips.
Usage:
• Graphics systems (shapes and groups of shapes).
Decorator Pattern
• Adds new behavior to objects dynamically without changing the class.
Usage:
• Adding features without creating many subclasses.
• Follows Open/Closed Principle.
Conclusion
Design Patterns help to:
• Write clean and reusable code
• Reduce complexity
• Improve communication between objects.