Software Design Pattern
In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. They provide a template for how to solve a problem that can be used in many different situations, promoting best practices and improving code maintainability and scalability.
Common Design Patterns
-
Creational Patterns: Deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.
- Singleton Pattern: Ensures a class has only one instance and provides a global point of access to it.
- Factory Pattern: Defines an interface for creating objects but allows subclasses to alter the type of objects that will be created.
- Builder Pattern: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
- Prototype Pattern: Specifies the kinds of objects to create using a prototypical instance and creates new objects by copying this prototype.
-
Structural Patterns: Deal with object composition, creating relationships between objects to form larger structures while keeping them flexible and efficient.
- Adapter Pattern: Converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together.
- Decorator Pattern: Allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.
- Facade Pattern: Provides a simplified interface to a larger body of code, such as a complex subsystem, making it easier to use and understand.
-
Behavioral Patterns: Focus on communication between objects, what goes on between objects and how they operate together.
- Observer Pattern: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
- Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable, allowing the algorithm to vary independently from clients that use it.
- Command Pattern: Encapsulates a request as an object, thereby allowing parameterization of clients with queues, requests, and operations.
- State Pattern: Allows an object to alter its behavior when its internal state changes, appearing to change its class.
Singleton Pattern
Section titled “Singleton Pattern”The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. This is useful when exactly one object is needed to coordinate actions across the system.
Use Cases
Section titled “Use Cases”The Singleton Pattern is commonly used in scenarios where exactly one instance of a class is needed to coordinate actions across the system. Typical use cases include:
- Configuration Management: Ensuring a single point of access to configuration settings.
- Logging: Providing a single, centralized logging instance.
- Resource Management: Managing access to shared resources such as database connections or thread pools.
- Caching: Maintaining a single cache instance to store frequently accessed data.
Implementation
Section titled “Implementation”class Singleton: _instance = None
def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance
# Usagesingleton1 = Singleton()singleton2 = Singleton()print(singleton1 is singleton2) # Trueclass Singleton { constructor() { if (Singleton.instance) { return Singleton.instance; } Singleton.instance = this; }}
// Usageconst singleton1 = new Singleton();const singleton2 = new Singleton();console.log(singleton1 === singleton2); // trueFactory Pattern
Section titled “Factory Pattern”The Factory Pattern is a creational design pattern that delegates object creation to a specialized method or class instead of calling constructors directly. This decouples your core business logic from concrete implementations.
Variations
Section titled “Variations”- Simple Factory (Not a formal GoF pattern): A single class or static method with a switch or if-else statement that decides which object to instantiate based on an input.
- Factory Method: Relies on subclassing/inheritance; an abstract creator defines the creation interface, and subclasses decide which concrete class to instantiate.
- Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
Use Cases
Section titled “Use Cases”- Database Connectors: An application needs to connect to MySQL, PostgreSQL, or MongoDB. A
DatabaseFactoryreads a configuration file and returns the correct connection object dynamically. - UI Component Libraries: A UI framework might need to create buttons, modals, or input fields based on the platform (web, mobile). A
UIFactorycan generate the appropriate components without the core logic knowing the exact class. - Logging Frameworks: A logging system might need to create different types of loggers (console, file, remote). A
LoggerFactorycan provide the correct logger based on configuration or environment.
Implementation
Section titled “Implementation”from abc import ABC, abstractmethod
class Vehicle(ABC): @abstractmethod def get_type(self) -> str: pass
class Car(Vehicle): def get_type(self) -> str: return "Car"
class Bike(Vehicle): def get_type(self) -> str: return "Bike"
class VehicleFactory(ABC): @abstractmethod def create_vehicle(self, vehicle_type) -> Vehicle: pass
class CarFactory(VehicleFactory): def create_vehicle(self, vehicle_type) -> Vehicle: return Car()
class BikeFactory(VehicleFactory): def create_vehicle(self, vehicle_type) -> Vehicle: return Bike()
carFactory = CarFactory()bikeFactory = BikeFactory()
myCar = carFactory.create_vehicle("Car")myBike = bikeFactory.create_vehicle("Bike")
myCar.get_type() # "Car"myBike.get_type() # "Bike"class Vehicle { getType() { throw new Error("Method 'getType()' must be implemented."); }}
class Car extends Vehicle { getType() { return "Car"; }}
class Bike extends Vehicle { getType() { return "Bike"; }}
class VehicleFactory { createVehicle(vehicleType) { throw new Error("Method 'createVehicle()' must be implemented."); }}
class CarFactory extends VehicleFactory { createVehicle(vehicleType) { return new Car(); }}
class BikeFactory extends VehicleFactory { createVehicle(vehicleType) { return new Bike(); }}
const carFactory = new CarFactory();const bikeFactory = new BikeFactory();
const myCar = carFactory.createVehicle("Car");const myBike = bikeFactory.createVehicle("Bike");
console.log(myCar.getType()); // "Car"console.log(myBike.getType()); // "Bike"