BCS1430
Dr. Ashish Sai
๐ Week 4 Lecture 2
๐ป BCS1430.ashish.nl
๐ EPD150 MSM Conference Hall
Design patterns are typical solutions to recurring design problems in software engineering.
Essence of Design Patterns
Patterns ๐จ: Not Just Code
Algorithms ๐งฎ: Step-by-step procedures for solving problems, like cooking recipes.
Design Patterns ๐จ: Abstract, flexible schemes for software structure, similar to architectural blueprints.
๐๏ธ
๐
๐ก
Adaptation to Software ๐จโ๐ป:
Gang of Four (GoF) ๐:

Patterns emerge when a solution is repeated across various projects, eventually gaining a name and detailed description.
Problem-Solving Toolkit ๐ ๏ธ : Offers proven solutions for common problems, improving problem-solving skills.
Design Vocabulary ๐จโ๐จ : Creates a common language for developers, enhancing communication and collaboration.
Best Practices โ : Promotes best practices in software design for maintainable and scalable code.
If all you have is a hammer ๐จ , everything looks like a nail.
Understanding the limitations and appropriate use of design patterns is crucial.
Creational patterns are fundamental for object creation in software design. They provide mechanisms that increase flexibility and reuse of existing code.
| Pattern | Description | Covered |
|---|---|---|
| Factory Method | Delegates the creation of objects to subclasses, promoting flexibility and integration. | โ |
| Abstract Factory | Creates families of related or dependent objects without specifying their concrete classes. | โ |
| Builder | Constructs complex objects step by step, allowing the creation process to create different types and representations of an object. | โ |
| Prototype | Creates new objects by copying an existing object, known as the prototype. | โ |
| Singleton | Ensures a class has only one instance while providing a global point of access to it. | โ |
Note: Simple Factory is not a true design pattern
Create an interface animal with some subclasses?
Subclasses:

Animal
Cat, Dog and DuckAnimalFactory
BalancedAnimalFactory and RandomAnimalFactoryFactory Method is a creational design pattern that provides an interface/contract for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. Itโs also known as Virtual Constructor.
The Factory Method pattern is designed to:
Provide an interface for object creation in a superclass.
Allow subclasses to change the type of objects created.
Promote loose coupling and scalability in the codebase.
Imagine a logistics management application:
Initially handles transportation by trucks (Truck class).
Needs to incorporate sea transportation (Ship class) due to popular demand.
Directly adding new classes leads to code tightly coupled with the Truck class, making the system inflexible and hard to maintain.
The Factory Method pattern suggests:
new) with calls to a special factory method.This diagram represents the basic structure of the Factory Method pattern.
public class Truck implements Transport {
public void deliver() {
System.out.println("Delivery by land in a box.");
}
}
public class Ship implements Transport {
public void deliver() {
System.out.println("Delivery by sea in a container.");
}
}
public class RoadLogistics extends Logistics {
public Transport createTransport() {
return new Truck();
}
}
public class SeaLogistics extends Logistics {
public Transport createTransport() {
return new Ship();
}
}Use the Factory Method when:
The exact types and dependencies of objects are not known beforehand.
You want to provide users with a way to extend internal components of a library or framework.
You want to save system resources by reusing existing objects instead of rebuilding them.
Pros:
Avoids tight coupling between creator and concrete products.
Adheres to the Single Responsibility and Open/Closed Principles.
Simplifies code maintenance and extension.
Cons:

The Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.
When the system needs to be independent of how its objects are created
When the family of related objects is designed to be used together
Imagine creating a furniture shop simulator with families of products like Chair, Sofa, and CoffeeTable, available in Modern, Victorian, and ArtDeco styles.
The challenge is ensuring that furniture pieces match in style without changing the code for new product additions.
Abstract Products declare interfaces for a set of distinct but related products forming a product family.
Concrete Products are implementations of abstract products, grouped by variants.
The Abstract Factory interface declares a set of creation methods for all abstract products.
Each Concrete Factory corresponds to a specific variant of products and creates only those product variants.
Chair, Sofa) and making all variants follow these interfaces.Clients interact with factories and products through abstract types, allowing the flexibility to change factory and product types dynamically.
Pros:
Ensures products are compatible with each other.
Decouples client code from concrete product classes.
Adheres to Single Responsibility and Open/Closed Principles.
Cons:
A creation method within a class is responsible for creating instances. This term generally refers to any method whose primary purpose is to create and return a new object.
public class Number {
private int value;
public Number(int value) {
this.value = value;
}
public Number next() {
return new Number(this.value + 1);
}
}Here, next is a creation method, producing a new Number instance.
Static creation methods allow calling a method on the class itself to create an instance, often providing clarity and control over the instantiation process.
public class User {
private int id;
private String name, email, phone;
private User(int id, String name, String email, String phone) {
this.id = id;
this.name = name;
this.email = email;
this.phone = phone;
}
public static User fromId(int id) {
// Fetch and construct user from id
return new User(id, "Name", "Email", "Phone");
}
}fromId is a static creation method, simplifying user creation from an ID.
The Simple Factory encapsulates object creation for a specific type, often based on given parameters.
public class SimpleFactory {
public static Object createObject(String type) {
if ("A".equals(type)) {
return new ProductA();
} else if ("B".equals(type)) {
return new ProductB();
}
throw new IllegalArgumentException("Unknown type");
}
}This pattern centralizes and simplifies object creation.
The Singleton Pattern is a design pattern that:
This pattern is useful for coordinating actions across a system.
The Singleton pattern addresses two primary issues: - ensuring a single instance and providing a global access point.
These capabilities are vital for controlling access to shared resources and preventing inconsistencies in the application state.
Singleton implementation involves making the constructor private and providing a static method that returns the same instance.
Java Code:
Private Instance: Add a private static field to store the singleton instance.
Public Creation Method: Implement a public static method for retrieving the singleton instance.
Lazy Initialization: Initialize the singleton lazily to ensure itโs created only when needed.
Implementing lazy initialization ensures the Singleton instance is created only when itโs first requested, optimizing resource usage and application performance.
Java Code:
Pros: - Guaranteed single instance.
Global access point.
Lazy initialization.
Cons: - Single Responsibility Principle violation.
Can mask bad design.
Requires special handling in multithreaded scenarios.
Java Code:
public class Database {
private static Database instance;
private Database() {}
public static synchronized Database getInstance() {
if (instance == null) {
instance = new Database();
}
return instance;
}
public void query(String sql) {
// Implementation here
}
}This example shows a Singleton used for database connections, a common use case in many applications.