Welcome to our series on Design Patterns. In this series, we will explore key design patterns from the book “Head First Design Patterns”.
The strategy pattern is a fundamental design pattern that is essential for understanding composition over inheritance. It is defined as:
quack are shared.fly method to Duck class leads to issues.fly and quack behaviors into different strategies.Different types of ducks inherit from Duck class.
Each subclass implements its own display method.
Promotes flexible code structure.
Allows behaviors to change dynamically.
Reduces dependency on inheritance.
Behaviors are not hard-coded in the Duck class.
They can vary independently from the duck type.
The Strategy Pattern is a powerful tool for creating flexible, maintainable code.
Encourages composition over inheritance.
Enables dynamic behavior assignment.
Push Model: Subject sends detailed data to observers.
Pull Model: Observers request data from the subject.
An introduction to the Decorator Pattern in software design.
Understanding its application in Java with practical examples.
Design patterns provide solutions to common software design problems.
The Decorator Pattern is one of several key patterns in object-oriented design.
Source: “Head First Design Patterns” book.
The need to extend the functionality of objects dynamically.
Avoiding “class explosion” for similar yet distinct objects.
Example: Different types of coffee in a coffee house application.
Multiple classes for each combination of coffee and add-ons (e.g., Espresso with Caramel, Decaf with Soy, etc.).
Results in a large, unmanageable number of subclasses.
A structural pattern for dynamically adding responsibilities to objects.
Avoids subclassing and promotes flexible design.
Consider a coffee ordering system.
Decorators for each add-on (e.g., caramel, soy milk).
public class CaramelDecorator extends AddOnDecorator {
public CaramelDecorator(Beverage beverage) {
this
beverage = beverage;
}
public int cost() {
return beverage.cost() + 2; // Adding cost of caramel
}
}
public class SoyDecorator extends AddOnDecorator {
public SoyDecorator(Beverage beverage) {
this.beverage = beverage;
}
public int cost() {
return beverage.cost() + 1; // Adding cost of soy
}
}Creating a coffee with add-ons.
Calculating the total cost dynamically.
Flexibility in adding new functionality.
Avoids class explosion by using composition over inheritance.
Easier to maintain and extend.
Can lead to complex code structures.
Difficulty in debugging, as it introduces layers of abstraction.
Potential performance issues due to increased object creation.
Decorator pattern used extensively in Java I/O classes.
Example: BufferedInputStream wraps an InputStream.
Similar structure but different intent.
Composite builds a hierarchy of objects.
Provides a surrogate or placeholder for another object.
Similar wrapping concept but for different purposes.
Illustrating the dynamic nature of the Decorator Pattern.
Composing beverages with multiple add-ons at runtime.
Decorator Pattern allows for more flexibility than subclassing.
Avoids rigid class hierarchy.
Promotes loose coupling and adherence to the Open-Closed Principle.
Ensure clarity in your decorator and component interfaces.
Avoid overuse of the pattern to prevent excessive complexity.
Consider the impact on system design and maintenance.
Decorator Pattern adds responsibilities to objects dynamically.
Enhances flexibility and reusability in object-oriented design.
Balances between complexity and extensibility.
Applied effectively in scenarios requiring runtime modification of behavior.
Note: Simple Factory is not a true design pattern
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
Design Patterns are typical solutions to common problems in software design.
Each pattern is like a blueprint that can be customized to solve a particular design problem in your code.
Reference Book: “Head First Design Patterns”.
The Factory Method Pattern defines an interface for creating an object but lets subclasses decide which class to instantiate.
It allows a class to defer instantiation to subclasses.
Key Components:
Creator (Interface or Abstract Class)
Concrete Creator
Product (Interface or Abstract Class)
Concrete Product
The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
It’s a step above the Factory Method Pattern.
Useful for creating a suite of related products.
Factory Method: Creates objects through inheritance.
Abstract Factory: Creates families of related objects without specifying their concrete classes.
Focus on group of products rather than one.
public interface AbstractFactory {
AbstractProductA createProductA();
AbstractProductB createProductB();
}
public class ConcreteFactory1 implements AbstractFactory {
public AbstractProductA createProductA() {
return new ConcreteProductA1();
}
public AbstractProductB createProductB() {
return new ConcreteProductB1();
}
}
// Similar implementation for ConcreteFactory2, ConcreteProductA2, and ConcreteProductB2Abstract Factory is ideal for complex creation processes involving multiple steps.
It can manage dependencies between different products.
Example: Creating a cohesive UI theme (Dark, Light) with compatible components (Buttons, Labels).
Abstract Factory assists in managing dependencies between objects.
Ensures that objects which are meant to work together are compatible.
Example: Ensuring that MacOS Alert Dialogues use MacOS Buttons, not Windows Buttons.
Use Abstract Factory for platform-independent UI creation.
Factories for each platform (MacOS, Windows, Linux) ensure compatible UI elements.
Streamlines development for multi-platform applications.
Guarantees that created objects are consistent with each other.
Prevents mixing incompatible components.
Example: A MacOS alert box will not mistakenly use a Windows button.
Offers flexibility in creating families of objects.
Factories can be easily switched to change the family of created objects.
Useful in scenarios like switching themes or platforms.
Ideal for scenarios like theme switching in an application.
Dark and Light theme factories create UI components with consistent styling.
Simplifies dynamic theme changes in the application.
Consistency: Ensures products from a family are compatible.
Flexibility: Easy to introduce new families of products.
Scalability: Simplifies adding new products to existing families.
Complexity: Can be overkill for simple scenarios.
Modifiability: Changing one part of the system can affect others.
Abstractness: High level of abstraction can be challenging to understand.
Abstract Factory can be combined with Dependency Injection for greater flexibility.
Factories are injected into classes that need to create objects.
This approach decouples the creation logic even further from usage.
UIControlFactory interface with methods like createButton(), createWindow().public interface UIControlFactory {
Button createButton();
Window createWindow();
}
public class DarkThemeUIControlFactory implements UIControlFactory {
public Button createButton() {
return new DarkThemeButton();
}
public Window createWindow() {
return new DarkThemeWindow();
}
}
public class LightThemeUIControlFactory implements UIControlFactory {
public Button createButton() {
return new LightThemeButton();
}
public Window createWindow() {
return new LightThemeWindow();
}
}The Singleton Pattern is a design pattern that:
This pattern is useful for coordinating actions across a system.
Thread safety is crucial in Singleton implementation, especially in multithreaded applications.
Imagine a chat application where you initially think there’s only one chat room.
This example illustrates how the assumption of a single instance can limit application scalability.
Singleton assumes you’ll never need more than one instance, but this isn’t always true.
Let’s delve deeper into the Singleton pattern with an advanced implementation.
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
// Private Constructor
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}This approach uses a static inner class for lazy initialization and is thread-safe without synchronization.
Instead of using Singleton, consider Dependency Injection (DI) for better testability and flexibility.
Singleton often violates the Single Responsibility Principle (SRP) by:
Consider splitting these responsibilities for better design.
Singleton introduces globals, which can lead to:
Singletons pose challenges for unit testing:
Singletons are often used in scenarios like:
Singleton pattern faces several criticisms:
The Singleton pattern and its impact on global state:
Origin: Discussed in “Head First Design Patterns” and “Design Patterns: Elements of Reusable Object-Oriented Software” by the Gang of Four.
Purpose: Encapsulates a request as an object.
Benefits:
Parameterization of objects with different requests.
Enabling queuing or logging of requests.
Supporting undoable operations.
Command Pattern Structure:
Command: An object encapsulating a request.
Invoker: Sends the command.
Receiver: The object receiving and executing the request.
Scenario: Controlling smart devices like lights, thermostats.
Application: Creating a smartphone app for device control.
Objective: Encapsulate each action (e.g., turning on a light) as a command.
Advantage: Commands can be passed and manipulated independently of the receiver.
Concept: Objects can be configured with commands to perform various actions.
Example: A remote control with buttons assigned to different light commands.
Queuing: Store and execute commands in sequence.
Logging: Keep a record of executed commands for auditing or replaying.
Implementation: Each command has an execute and undo method.
Use Case: Reversing a command, like turning off a light that was turned on.
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOn();
}
public void
undo() {
light.turnOff();
}
}LightOnCommand encapsulates the action of turning on a light.public class RemoteControl {
private Command[] commands;
public RemoteControl() {
commands = new Command[4]; // Assuming 4 buttons
}
public void setCommand(int slot, Command command) {
commands[slot] = command;
}
public void buttonPressed(int slot) {
if (commands[slot] != null) {
commands[slot].execute();
}
}
}RemoteControl: Acts as an invoker that triggers commands.Concept: A command that contains multiple commands.
Use Case: Executing a batch of commands with a single action.
Implementation: Commands can be added to a queue and executed in order.
Application: Useful for scheduling and executing tasks sequentially.
Concept: Providing an undo method in each command to reverse its action.
Implementation: Storing the history of executed commands for undo operations.
public class RemoteControlWithUndo {
private Command[] commands;
private Stack<Command> history = new Stack<>();
public void setCommand(int slot, Command command) {
commands[slot] = command;
}
public void pressedButton(int slot) {
if (commands[slot] != null) {
commands[slot].execute();
history.push(commands[slot]);
}
}
public void pressedUndo() {
if (!history.isEmpty()) {
history.pop().undo();
}
}
}RemoteControlWithUndo keeps track of command history for undo operations.Flexibility: Commands can be added, removed, or modified independently.
Reusability: Commands can be used across different contexts and applications.
Extensibility: Easy to add new commands without changing existing code.
Application: Assigning commands to UI elements like buttons, menus.
Example: A toolbar with buttons executing different commands in an application.
Concept: Combining multiple commands into a single composite command.
Use Case: Complex operations that require executing several commands in a sequence.
Object-Oriented Programming: Encapsulating actions as objects.
Functional Programming: Treating functions as first-class citizens, similar to commands in OOP.
Command Pattern: Encapsulates requests as objects, offering flexibility and extensibility.
Key Components: Command, Invoker, Receiver.
Benefits:
Decoupling of command execution from its invocation.
Support for undo operations.
Enhanced control over operations, including queuing and logging.
Applications: Widely used in GUIs, transactional systems, and more.
Understanding the core concepts of software design patterns.
Focus on Adapter, Facade, Proxy, and Decorator patterns.
Reference Book: Head First Design Patterns.
Patterns as solutions to common software design problems.
Patterns provide a standard terminology and specific to problems.
Four key patterns: Adapter, Facade, Proxy, and Decorator.
Purpose: To make two incompatible interfaces compatible.
Also known as a “wrapper.”
Use Case: Connecting new code to legacy code or third-party libraries.
// Target Interface
public interface MediaPlayer {
void play(String audioType, String fileName);
}
// Adapter Class
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new VlcPlayer();
} else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
} else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}Simplifies complex system interactions.
Provides a unified interface to a set of interfaces in a subsystem.
Example: Starting a car (Key Turn → Engine Start, Lights On, etc.)
// Facade Class
public class CarEngineFacade {
private Ignition ignition;
private FuelInjector fuelInjector;
private AirFlowController airFlowController;
public CarEngineFacade() {
ignition = new Ignition();
fuelInjector = new FuelInjector();
airFlowController = new AirFlowController();
}
public void startEngine() {
fuelInjector.on();
airFlowController.takeAir();
ignition.ignite();
// Other complex interactions
}
public void stopEngine() {
fuelInjector.off();
airFlow
Controller.cutAir();
ignition.off();
// Other shutdown interactions
}
}Provides a surrogate or placeholder for another object.
Controls access to the original object.
Use cases: Security, Remote Object Access, Lazy Initialization.
// RealSubject Class
public class RealImage implements Image {
private String fileName;
public RealImage(String fileName){
this.fileName = fileName;
loadFromDisk(fileName);
}
@Override
public void display() {
System.out.println("Displaying " + fileName);
}
private void loadFromDisk(String fileName){
System.out.println("Loading " + fileName);
}
}
// Proxy Class
public class ProxyImage implements Image {
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName){
this.fileName = fileName;
}
@Override
public void display() {
if(realImage == null){
realImage = new RealImage(fileName);
}
realImage.display();
}
}Adds new functionality to an object dynamically.
More flexible than static inheritance.
Example: Adding scrolling to a window in a GUI framework.
// Component Interface
public interface Shape {
void draw();
}
// Concrete Component
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
// Decorator Class
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
public void draw(){
decoratedShape.draw();
}
}
// Concrete Decorator
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}Understanding the subtle differences.
Adapter vs. Facade vs. Proxy vs. Decorator.
Each solves specific design issues in object-oriented programming.
Adapter: Makes two incompatible interfaces work together.
Facade: Provides a simplified interface to a complex subsystem.
Comparison: Adapter changes the interface; Facade simplifies it.
Facade: Simplifies access to a complex system.
Proxy: Controls access to an object, often adding additional functionality.
Comparison: Facade is structural; Proxy often adds behavior.
Proxy: Acts as an intermediary for another object.
Decorator: Adds responsibilities to an object dynamically.
Comparison: Proxy controls access; Decorator enhances functionality.
Adapter: Allows otherwise incompatible interfaces to work together.
Decorator: Enhances an object with additional features.
Comparison: Adapter is about compatibility; Decorator is about enhancement.
Reviewed key design patterns: Adapter, Facade, Proxy, and Decorator.
Discussed the importance and application of each pattern.
Highlighted differences and specific use cases.
Recommended reading: Head First Design Patterns for deeper understanding.
Focus: Facade Pattern
Context: Software Design Patterns
References:
“Design Patterns: Elements of Reusable Object-Oriented Software” by Gang of Four
“Head First Design Patterns”
Definition: Simplifies complex system interactions
Purpose: Provide a unified interface to a set of interfaces in a subsystem
Key Principle: High-level abstraction over complex subsystems
Scenario: Multiple classes with intricate interactions
Challenge: Managing complex dependencies and interactions
Client: User of a piece of code, not end-user
Problem: Need to interact with complex subsystems
Principle: Minimize coupling between modules
Rule: Object should only talk to immediate friends
Simplified: a.B() is allowed, but a.B().C() is not
Concept: Each class should have one responsibility
Benefit: Easier maintenance and understanding
Complexity: High due to multiple, interdependent classes
Solution: Simplify interaction using a facade
public class ComplexSystemFacade {
private SubsystemOne one;
private SubsystemTwo two;
private SubsystemThree three;
public ComplexSystemFacade() {
one = new SubsystemOne();
two = new SubsystemTwo();
three = new SubsystemThree();
}
public void simplify() {
one.operation();
two.operation();
three.operation();
}
}
class SubsystemOne { void operation() {} }
class SubsystemTwo { void operation() {} }
class SubsystemThree { void operation() {} }Simplicity: Provides simple interface to complex subsystems
Decoupling: Clients interact with facade rather than direct subsystem
Maintainability: Changes in subsystems less likely to affect clients
Proxy Pattern in Software Design
Part of the Structural Patterns
Key Concept: Controlling access to another object
Fundamental to software engineering
Provides solutions to common problems
Enhances code maintainability and flexibility
Acts as a surrogate or placeholder
Manages access to another object
Adds a level of indirection in object access
Remote Proxy: Accessing remote resources
Virtual Proxy: Managing expensive resource creation
Protection Proxy: Controlling access based on permissions
Used for interacting with remote resources
Example: Data from a different server
Acts as an intermediary for remote method calls
Controls access to resource-intensive objects
Delays the creation of the object until necessary
Example: Lazy initialization for performance optimization
Manages access based on access rights
Ensures only authorized access to an object
Common in scenarios requiring security and permissions
public interface BookParser {
int getNumberOfPages();
}
public class RealBookParser implements BookParser {
private String bookContent;
public RealBookParser(String bookContent) {
// Expensive parsing operation
this.bookContent = bookContent;
}
@Override
public int getNumberOfPages() {
// Return calculated pages
return 0; // Simplified for example
}
}
public class LazyBookParserProxy implements BookParser {
private RealBookParser realParser;
private String bookContent;
public LazyBookParserProxy(String bookContent) {
this.bookContent = bookContent;
}
@Override
public int getNumberOfPages() {
if (realParser == null) {
realParser = new RealBookParser(bookContent);
}
return realParser.getNumberOfPages();
}
}Proxy mimics the real object
Transparent to the client
Adds control layer over real object access
public interface RemoteService {
String fetchData();
}
public class RemoteServiceImpl implements RemoteService {
public String fetchData() {
// Simulates fetching data over network
return "Data";
}
}
public class RemoteProxy implements RemoteService {
private RemoteService remoteService = new RemoteServiceImpl();
public String fetchData() {
// Additional control logic can be added here
return remoteService.fetchData();
}
}public interface Image {
void display();
}
public class HighResolutionImage implements Image {
public HighResolutionImage(String imagePath) {
// Load image from disk - heavy operation
}
public void display() {
// Display the image
}
}
public class ImageProxy implements Image {
private HighResolutionImage highResImage;
private String imagePath;
public ImageProxy(String imagePath) {
this.imagePath = imagePath;
}
public void display() {
if (highResImage == null) {
highResImage = new HighResolutionImage(imagePath);
}
highResImage.display();
}
}public interface SecureResource {
void accessResource();
}
public class RealResource implements SecureResource {
public void accessResource() {
// Access the secure resource
}
}
public class SecurityProxy implements SecureResource {
private RealResource realResource;
private boolean hasAccess;
public SecurityProxy(boolean hasAccess) {
this.realResource = new RealResource();
this.hasAccess = hasAccess;
}
public void accessResource() {
if (hasAccess) {
realResource.accessResource();
} else {
throw new IllegalStateException("Access Denied");
}
}
}Used in API gateways
Manages requests to various microservices
Adds security, load balancing, and caching
Manages database connections
Provides a layer for security and transaction management
Example: Hibernate uses proxies for lazy loading
Defers object creation until needed
Reduces initial load time
Common in resource-intensive applications
Logs and monitors access to objects
Useful in security-sensitive applications
Proxy adds logging mechanism transparently
Separation of concerns
Enhanced security
Flexibility and scalability
Increased complexity
Potential performance overhead
Proxy pattern is a fundamental structural design pattern
Provides control over access to objects
Versatile with various applications in software development
Requires careful implementation to balance benefits and complexity
This presentation explores design patterns in software engineering, with a focus on the Bridge Pattern.
Design Patterns: Reusable solutions to common problems in software design.
Bridge Pattern: A structural design pattern that decouples an abstraction from its implementation.
Before diving into the Bridge pattern, let’s understand the problem it addresses:
Coupling: Tight coupling between an abstraction (interface) and its implementation (concrete classes).
Inflexibility: Difficulty in extending or modifying abstractions and implementations independently.
The Bridge pattern addresses the issues of tight coupling and inflexibility.
Decouples abstraction from its implementation.
Independence: Abstractions and implementations can vary independently.
Abstraction: Defines the abstract interface.
Refined Abstraction: Extends the abstraction with additional features.
Implementor: Defines the interface for implementation classes.
Concrete Implementor: Implements the implementor interface.
Consider an application displaying various media types (e.g., books, artists) in different formats (e.g., long-form, short-form).
Problem: How to handle different media types and display formats without creating a complex class hierarchy?
Solution: Use the Bridge pattern for flexible and maintainable code.
// Refined Abstraction (LongFormView.java)
public class LongFormView extends View {
public LongFormView(MediaResource resource) {
super(resource);
}
public void show() {
// Show in long-form format
resource.display();
}
}
// Refined Abstraction (ShortFormView.java)
public class ShortFormView extends View {
public ShortFormView(MediaResource resource) {
super(resource);
}
public void show() {
// Show in short-form format
resource.display();
}
}Flexibility: Allows abstraction and implementation to vary independently.
Extensibility: Easy to extend both hierarchies without affecting each other.
Single Responsibility Principle: Separates high-level logic from low-level details.
The Bridge pattern emphasizes decoupling abstraction (e.g., View) from its implementation (e.g., MediaResource) for greater flexibility and maintainability.
Think of the Bridge pattern like a TV remote (abstraction) and a TV (implementation). The remote can control different TVs (implementations), and TVs can be operated by different remotes (abstractions).
When you want to avoid a permanent binding between an abstraction and its implementation.
When both the abstractions and their implementations should be extensible by subclassing.
In applications where implementation details need to be hidden from the client.
Bridge: Designed up-front to separate abstraction and implementation.
Adapter: Used to make unrelated classes work together after they are designed.
Refactoring a tightly coupled system using the Bridge pattern leads to more modular and maintainable code. It simplifies future changes and extensions to both abstractions and implementations.
// Example implementation of the Bridge pattern in Java
// Abstraction
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract public void draw();
}
// Implementor
public interface Color {
public void fill();
}
// Refined Abstraction
public class Circle extends Shape {
public Circle(Color color) {
super(color);
}
public void draw() {
System.out.println("Drawing Circle");
color.fill();
}
}
// Concrete Implementor
public class RedColor implements Color {
public void fill() {
System.out.println("Filling with red color");
}
}Analyze your application’s requirements to determine if the Bridge pattern is suitable.
Identify the orthogonal dimensions in your design (e.g., UI vs media types).
Use the Bridge pattern when you expect numerous variations in both dimensions.
Complexity: Introduces additional layers which may complicate the code structure.
Overhead: May lead to a performance penalty due to increased indirection.
Suitability: Not ideal for simpler designs where flexibility isn’t a primary concern.
The Bridge pattern is a powerful tool for managing abstractions and implementations separately.
It offers flexibility, extensibility, and adherence to the Single Responsibility Principle.
Suitable for complex systems where variations in both abstractions and implementations are expected.
This lecture covers a comparison of several key structural design patterns in object-oriented programming:
Reference Books: - Head First Design Patterns - Design Patterns: Elements of Reusable Object-Oriented Software
Definition: Decouples an abstraction from its implementation so that the two can vary independently.
UML Diagram:
// Abstraction
abstract class Abstraction {
protected Implementor implementor;
protected Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
// Refined Abstraction
class RefinedAbstraction extends Abstraction {
protected RefinedAbstraction(Implementor implementor) {
super(implementor);
}
public void operation() {
implementor.implementation();
}
}
// Implementor
interface Implementor {
void implementation();
}
// Concrete Implementors
class ConcreteImplementorA implements Implementor {
public void implementation() {
// Implementation A
}
}
class ConcreteImplementorB implements Implementor {
public void implementation() {
// Implementation B
}
}Definition: Allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
UML Diagram:
// Target Interface
interface Target {
void request();
}
// Adaptee
class Adaptee {
void specificRequest() {
// Specific Request
}
}
// Adapter
class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
public void request() {
adaptee.specificRequest();
}
}
// Client
class Client {
private Target target;
Client(Target target) {
this.target = target;
}
void execute() {
target.request();
}
}Definition: Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
UML Diagram:
// Component Interface
interface Component {
void operation();
}
// Concrete Component
class ConcreteComponent implements Component {
public void operation() {
// Original Operation
}
}
// Decorator
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
// Concrete Decorators
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
// Additional Behavior A
}
}
class ConcreteDecoratorB extends Decorator {
private String addedState;
public ConcreteDecoratorB(Component component, String addedState) {
super(component);
this.addedState = addedState;
}
public void operation() {
super.operation();
// Use addedState in operation
}
}Definition: Provides a surrogate or placeholder for another object to control access to it.
UML Diagram:
// Subject Interface
interface Subject {
void request();
}
// Real Subject
class RealSubject implements Subject {
public void request() {
// Real request handling
}
}
// Proxy
class Proxy implements Subject {
private RealSubject realSubject = new RealSubject();
public void request() {
// Access control, then delegate to real subject
realSubject.request();
}
}
// Client
class Client {
private Subject subject;
Client(Subject subject) {
this.subject = subject;
}
void execute() {
subject.request();
}
}Definition: Provides a unified interface to a set of interfaces in a subsystem, making the subsystem easier to use.
UML Diagram:
// Subsystem Class A
class SubsystemClassA {
void operationA1() {
// Operation A1
}
void operationA2() {
// Operation A2
}
}
// Subsystem Class B
class SubsystemClassB {
void operationB1() {
// Operation B1
}
void operationB2() {
// Operation B2
}
}
// Facade
class Facade {
private SubsystemClassA subsystemA = new SubsystemClassA();
private SubsystemClassB subsystemB = new SubsystemClassB();
void method() {
subsystemA.operationA1();
subsystemA.operationA2();
subsystemB.operationB1();
subsystemB.operationB2();
}
}
// Client
class Client {
private Facade facade = new Facade();
void execute() {
facade.method();
}
}We’ll now compare the structural design patterns discussed, focusing on their intent and structural differences.
Decorator: Adds behavior to an object dynamically.
Adapter: Bridges incompatible interfaces.
Facade: Simplifies complex system interfaces.
Proxy: Controls access to an object.
Bridge: Decouples abstraction from its implementation.
Decorator Pattern:
Adds responsibilities to objects.
Enhances object functionalities.
Uses composition to extend behavior.
Adapter Pattern:
Bridges the gap between incompatible interfaces.
Converts one interface to another.
Does not change the underlying object’s functionality.
Facade Pattern: - Provides a simplified interface to a complex system. - Does not change the subsystem behavior. - Often used to encapsulate third-party libraries or complex subsystems.
Proxy Pattern:
Controls access to an object.
Can add additional behavior like lazy initialization, access control, logging.
Acts as a surrogate for the actual object.
Bridge Pattern:
Separates an object’s interface from its implementation.
Allows for independent variation of an abstraction and its implementation.
Useful when both the interface and implementations can have different variations.
Choosing the right pattern depends on the problem context:
Complexity Reduction: Facade if simplifying complex interactions is needed.
Interface Compatibility: Adapter when interfacing with incompatible classes.
Dynamic Behavior Extension: Decorator for adding behaviors at runtime.
Access Control or Functionality Extension: Proxy for controlling object access.
Abstraction-Implementation Variation: Bridge when both aspects vary independently.
Scenario: Adding new features to a GUI component without modifying it.
interface GUIComponent {
void draw();
}
class Window implements GUIComponent {
public void draw() {
// Draw window
}
}
class BorderDecorator extends Decorator {
public BorderDecorator(GUIComponent component) {
super(component);
}
public void draw() {
super.draw();
drawBorder();
}
private void drawBorder() {
// Draw border around window
}
}Scenario: Integrating a third-party library with a different interface.
interface MediaPlayer {
void play(String audioType, String fileName);
}
class AdvancedMediaPlayer {
void playVLC(String fileName) {
// Play VLC media
}
void playMP4(String fileName) {
// Play MP4 media
}
}
class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
MediaAdapter(String audioType) {
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new AdvancedMediaPlayer(); // Assume VLC implementation
} else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new AdvancedMediaPlayer(); // Assume MP4 implementation
}
}
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVLC(fileName);
} else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMP4(fileName);
}
}
}Scenario: Simplifying a complex multimedia system.
class AudioSystem {
void playAudio(String file) {
// Play audio logic
}
}
class VideoSystem {
void playVideo(String file) {
// Play video logic
}
}
class MultimediaFacade {
private AudioSystem audioSystem = new AudioSystem();
private VideoSystem videoSystem = new VideoSystem();
void playMedia(String fileType, String fileName) {
if(fileType.equalsIgnoreCase("audio")) {
audioSystem.playAudio(fileName);
} else if(fileType.equalsIgnoreCase("video")) {
videoSystem.playVideo(fileName);
}
}
}
// Client uses Facade for simplified interface
class Client {
public static void main(String[] args) {
MultimediaFacade facade = new MultimediaFacade();
facade.playMedia("audio", "song.mp3");
facade.playMedia("video", "movie.mp4");
}
}Scenario: Implementing access control for a sensitive document.
interface Document {
void display();
}
class RealDocument implements Document {
private String fileName;
RealDocument(String fileName) {
this.fileName = fileName;
loadFromDisk(fileName);
}
void display() {
System.out.println("Displaying " + fileName);
}
private void loadFromDisk(String fileName) {
System.out.println("Loading " + fileName);
}
}
class ProxyDocument implements Document {
private RealDocument realDocument;
private String fileName;
ProxyDocument(String fileName) {
this.fileName = fileName;
}
void display() {
if(realDocument == null){
realDocument = new RealDocument(fileName);
}
realDocument.display();
}
}
// Client interacts with ProxyDocument
class Client {
public static void main(String[] args) {
Document document = new ProxyDocument("test.txt");
document.display(); // Loaded and displayed only when needed
}
}Scenario: Creating a multi-platform window rendering system.
// Abstraction
interface WindowRenderer {
void renderWindow(String title);
}
// Refined Abstraction
class IconWindow implements WindowRenderer {
private WindowImplementor implementor;
IconWindow(WindowImplementor implementor) {
this.implementor = implementor;
}
public void renderWindow(String title) {
implementor.drawWindow(title);
implementor.drawIcon();
}
}
// Implementor
interface WindowImplementor {
void drawWindow(String title);
void drawIcon();
}
// Concrete Implementor A
class LinuxWindowImplementor implements WindowImplementor {
public void drawWindow(String title) {
System.out.println("Drawing Window in Linux style: " + title);
}
public void drawIcon() {
System.out.println("Drawing Icon in Linux style");
}
}
// Concrete Implementor B
class WindowsWindowImplementor implements WindowImplementor {
public void drawWindow(String title) {
System.out.println("Drawing Window in Windows style: " + title);
}
public void drawIcon() {
System.out.println("Drawing Icon in Windows style");
}
}Decorator is often used for small, dynamic, and single-object modifications.
Adapter is ideal for making existing classes work with others without modifying their source code.
Facade simplifies complex systems, providing a unified interface.
Proxy is used for controlled access or additional layer, like lazy initialization or security.
Bridge decouples abstraction from implementation, providing flexibility in large-scale applications.
Fundamental concepts in software engineering.
Solutions to common problems in software design.
They provide a template for how to solve a problem.
One of the behavioral design patterns.
Defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.
Promotes code reuse.
Provides a clear structure for algorithms.
Facilitates flexibility and customization.
public class Football extends Game {
@Override
protected void initialize() {
System.out.println("Football Game Initialized.");
}
@Override
protected void startPlay() {
System.out.println("Football Game Started.");
}
@Override
protected void endPlay() {
System.out.println("Football Game Finished.");
}
}The abstract class defines a template method setting up the structure.
Concrete classes implement these steps without changing the structure.
Allows for customization within a fixed framework.
Simplifies code maintenance.
Promotes code reusability and scalability.
Enhances standardization of an algorithm.
“Don’t call us, we’ll call you.”
High-level components make decisions about when to call low-level components.
This principle is integral to the Template Method pattern.
Classes should be open for extension, but closed for modification.
The Template Method pattern adheres to this principle by allowing extension through subclassing.
Incorporates hooks and operations.
Hooks are optional steps in the algorithm, defined in the abstract class.
Concrete classes can override these hooks to add custom behavior.
@startuml
abstract class AbstractClass {
templateMethod(): void {
primitiveOperation1();
hook();
primitiveOperation2();
}
abstract primitiveOperation1()
abstract primitiveOperation2()
hook() { }
}
class ConcreteClass extends AbstractClass {
primitiveOperation1()
primitiveOperation2()
hook()
}
AbstractClass -> ConcreteClass : uses
@endumlpublic abstract class GameWithHooks {
// Template method with a hook
public final void play() {
initialize();
startPlay();
if (addNewGameFeature()) {
addFeature();
}
endPlay();
}
// Hook
protected boolean addNewGameFeature() {
return false;
}
// New feature
protected void addFeature() {}
// Other methods same as previous Game example
}Template Method often uses inheritance.
However, composition can be a more flexible alternative.
This involves defining the algorithm in a separate class and composing it in concrete classes.
Both design patterns are about defining algorithms.
Strategy Pattern allows changing the behavior dynamically.
Template Method defines a fixed algorithm structure, with specific steps being variable.
Subtypes must be substitutable for their base types.
Essential for the Template Method to ensure derived classes can replace base classes without affecting the algorithm.
Template Method is widely used in frameworks and libraries.
It provides a defined structure while allowing users to extend specific functionality.
Examples: Data parsing libraries, game development frameworks, UI rendering engines.
Introduction to design patterns in object-oriented programming
Focus on the Composite pattern
Applications and significance
Structural pattern in object-oriented programming
Simplifies client interaction with complex tree structures
Treats individual objects and compositions uniformly
Composite objects: Objects made up of multiple, smaller objects
Uniform treatment of individual and composite objects
Example: File system directories and files
Reduces complexity in client code
Enhances flexibility in adding new types
Encourages modular, maintainable code design
Component: Common interface for all objects
Leaf: Basic element of the structure
Composite: A collection of Components
Defines the operation method
Base for Leaf and Composite classes
public class Leaf implements Component {
public void operation() {
// Implementation of leaf-specific behavior
}
}Simple element with no children
Implements operation method
import java.util.List;
import java.util.ArrayList;
public class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void operation() {
// Implementation for composite operation
for (Component child : children) {
child.operation();
}
}
public void add(Component component) {
children.add(component);
}
public void remove(Component component) {
children.remove(component);
}
public Component getChild(int n) {
return children.get(n);
}
}Manages child components
Implements and delegates operation
Simplifies client interaction with complex structures
Makes it easier to add new types of components
Promotes principle of polymorphism and reusability
Common real-world application
Directories (Composites) and Files (Leaves)
Simplifies file system navigation and management
Ideal for managing tree-like data structures
Example: GUI components, organizational hierarchies
Uniform operations on nodes and subtrees
Key feature for handling nested structures
Composite’s methods recursively call children’s methods
Simplifies complex operations
public class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void addChild(Component child) {
children.add(child);
}
public void removeChild(Component child) {
children.remove(child);
}
public Component getChild(int index) {
return children.get(index);
}
}Composite manages its children
Allows adding and removing child components
Composite and Leaf objects are used interchangeably
Client code remains simple and uniform
Enhances code flexibility and scalability
Iterators can be used for traversing composites
Simplifies complex tree traversal
Example: Iterating over nested menus in a GUI
Handling specific cases for Leaf and Composite
Avoiding excessive reliance on type checking
Designing for future extension and maintenance
Both manage object compositions
Composite: Uniform treatment of composites and leaves
Decorator: Add responsibilities to objects dynamically
Composite pattern simplifies complex tree structures
Enhances code reusability and maintainability
Suitable for applications with hierarchical data models
In this session, we’ll explore:
The Decorator Pattern
The Composite Pattern
Key differences and use-cases
Purpose: Dynamically add responsibilities to objects.
Use-case: Modify behavior at runtime without altering class structure.
Principle: Supports the Open-Closed Principle.
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() {
// Basic operation
}
}
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
}
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
// Additional behavior
component.operation();
}
}Purpose: Compose objects into tree structures.
Use-case: Represent part-whole hierarchies.
Key Point: Treat individual and composite objects uniformly.
interface Component {
void operation();
}
class Leaf implements Component {
public void operation() {
// Leaf operation
}
}
class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void add(Component component) {
children.add(component);
}
public void operation() {
// Composite operation
for (Component child : children) {
child.operation();
}
}
}Decorator focuses on adding responsibilities at runtime.
Composite deals with object structures and hierarchy.
Decorator Intent: Enhance functionality dynamically.
Composite Intent: Manage a group of objects as a single entity.
Structural Differences: Although visually similar, they serve distinct purposes.
Decorator: Used in GUI toolkits for adding features like scrolling, borders.
Composite: File systems, UI components where hierarchy is inherent.
Composite: Naturally hierarchical.
Decorator: Linear in structure; adds functionality layer by layer.
Ideal for data that is naturally hierarchical.
Simplifies client code for handling complex structures.
Provides flexibility to add/remove responsibilities at runtime.
Avoids subclassing and keeps class hierarchy simple.
Highlighting structural similarities and differences.
Decorator: Linear.
Composite: Hierarchical.
// Visual comparison of UML diagrams.
Decorator adds functionality without altering base class.
Composite manages tree-like structures.
Java examples to illustrate differences.
Decorator: Enhancing GUI components (e.g., adding scroll bars).
Composite: Building complex GUI layouts (e.g., panels containing buttons).
Composite: Representing files and directories.
Demonstrates the need for a unified interface to treat files and directories alike.
Both patterns utilize polymorphism.
Composite: Through tree structures.
Decorator: Through wrapping objects.
Understanding these patterns is crucial for effective OOP design.
Recommended Books:
“Design Patterns: Elements of Reusable Object-Oriented Software” by Gang of Four
“Head First Design Patterns”
Explore more patterns for deeper insights into OOP.
The Iterator Pattern is a fundamental design pattern in object-oriented programming. It provides a way to access the elements of a collection sequentially without revealing the underlying representation of the collection.
This pattern is essential for:
Providing a uniform way to traverse different data structures.
Decoupling the collection objects and the traversal logic.
Next, we’ll explore what collections are and the challenges faced without the Iterator Pattern.
A collection in programming is an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
Examples of collections:
A list of numbers.
A set of unique values.
A map of key-value pairs.
Understanding collections is key to realizing the importance of the Iterator Pattern.
Without the Iterator Pattern, traversing different types of collections can be challenging due to:
Diverse collection structures (arrays, trees, graphs).
The necessity to expose internal representation for iteration.
Increased complexity in client code due to direct traversal logic.
This lack of a unified traversal mechanism leads to less maintainable and more error-prone code.
The Iterator Pattern addresses these challenges by:
Providing a standard way to traverse through a collection.
Allowing the collection to manage the iteration logic internally.
Hiding the internal structure of the collection.
It simplifies client code and enhances maintainability.
This UML diagram illustrates the core components of the Iterator Pattern:
Iterator interface defines the iteration methods.
Aggregate interface provides a method to create an Iterator.
ConcreteIterator implements the Iterator interface for a specific collection.
ConcreteAggregate implements the Aggregate interface and holds the collection.
Here’s a simple implementation of an Iterator in Java:
public interface Iterator<T> {
boolean hasNext();
T next();
}
public class ConcreteIterator<T> implements Iterator<T> {
private T[] items;
private int index = 0;
public ConcreteIterator(T[] items) {
this.items = items;
}
@Override
public boolean hasNext() {
return index < items.length;
}
@Override
public T next() {
return items[index++];
}
}This code demonstrates a basic Iterator for an array of generic type T.
In game development, the Iterator Pattern can be used to manage collections like:
A list of enemies in a game world.
Inventory items in a player’s backpack.
It allows for efficient traversal and operation on these collections without exposing their internal structure.
This diagram represents how a GameWorld can create an EnemyIterator to iterate over its collection of enemies.
Implementing an Iterator for a game world’s enemy list:
public class EnemyIterator implements Iterator<Enemy> {
private GameWorld world;
private int index;
public EnemyIterator(GameWorld world) {
this.world = world;
this.index = 0;
}
@Override
public boolean hasNext() {
return index < world.getEnemies().size();
}
@Override
public Enemy next() {
return world.getEnemies().get(index++);
}
}This code snippet shows an Iterator tailored for iterating over enemies in a game world.
The Iterator Pattern adheres to the Single Responsibility Principle (SRP) by:
Separating the logic of iterating over a collection from the collection itself.
Allowing each class (iterator and collection) to manage its own responsibilities.
Advanced usage of iterators allows for more complex operations such as:
Filtering items while iterating.
Applying functions to each item in the collection.
Combining or chaining iterators for complex data structures.
These advanced techniques provide greater flexibility and power in handling collections.
@startuml
interface Iterator<T> {
+ hasNext(): Boolean
+ next(): T
}
class FilterIterator<T> implements Iterator<T> {
- wrappedIterator: Iterator<T>
- filterCondition: Predicate<T>
+ hasNext(): Boolean
+ next(): T
}
Iterator <|.. FilterIterator
@endumlThis diagram shows a FilterIterator that wraps around another iterator, providing additional filtering capabilities based on a given condition.
Implementing a FilterIterator in Java:
public class FilterIterator<T> implements Iterator<T> {
private Iterator<T> wrappedIterator;
private Predicate<T> filterCondition;
private T nextItem;
private boolean hasNextItem;
public FilterIterator(Iterator<T> iterator, Predicate<T> filter) {
this.wrappedIterator = iterator;
this.filterCondition = filter;
advance();
}
private void advance() {
hasNextItem = false;
while (wrappedIterator.hasNext()) {
T item = wrappedIterator.next();
if (filterCondition.test(item)) {
nextItem = item;
hasNextItem = true;
break;
}
}
}
@Override
public boolean hasNext() {
return hasNextItem;
}
@Override
public T next() {
if (!hasNextItem) {
throw new NoSuchElementException();
}
T item = nextItem;
advance();
return item;
}
}This code filters items in a collection based on a specified condition while iterating.
The Iterator Pattern complements functional programming concepts:
Iterators can be used in conjunction with streams and lambda expressions.
Enables operations like map, filter, and reduce on collections.
This integration brings a declarative approach to collection processing.
Comparing foreach loop and the Iterator Pattern:
foreach is syntactic sugar over iterators in many languages.
Iterators provide more control, e.g., removing elements during iteration.
Understanding this relationship helps in choosing the right iteration mechanism.
This diagram illustrates the integration of the Iterator Pattern in game logic. The GameLogic class uses an iterator to process enemies in the GameWorld.
Implementing game logic using the Iterator Pattern:
public class GameLogic {
private GameWorld world;
public GameLogic(GameWorld world) {
this.world = world;
}
public void processEnemies() {
Iterator<Enemy> iterator = world.getEnemyIterator();
while (iterator.hasNext()) {
Enemy enemy = iterator.next();
// Process each enemy
// e.g., enemy.takeDamage(10);
}
}
}This example shows how to iterate over and process game elements using an iterator.
The Iterator Pattern can also be adapted for infinite collections:
Useful for generating infinite sequences or streams.
Allows lazy evaluation: elements are generated only when needed.
This adaptation is powerful for certain types of data processing tasks.
This diagram represents an InfiniteIterator for an InfiniteCollection, illustrating how iteration can continue indefinitely.
Benefits of the Iterator Pattern:
Separates collection data and iteration logic.
Facilitates various types of traversals and operations.
Enhances code maintainability and readability.
Considerations:
Overhead of creating iterators.
Complexity in understanding and implementing advanced iterators.
The Iterator Pattern is a versatile tool in a developer’s toolkit, applicable in many scenarios with collections.
Objective: Understand the State design pattern in object-oriented programming.
Context: Managing states and behaviors in software systems.
Application: Example of a turnstile system in a subway.
A state machine is a well-studied concept in computer science.
Deals with states and transitions.
Memoryless: Decisions based on current state, not history.
Simplifies State Management: Clear structure for managing states.
Reduces Complexity: Avoids tangled conditional logic.
Adaptability: Easy to modify and add new states.
Object Behaviors: Change based on its state.
No Direct Dependency: On the history of how the state was reached.
Scenario: Subway turnstile system.
Focus: Managing turnstile states using State Pattern.
Closed: Default state. Cannot pass through.
Open: Allows passage. Transitions to closed after entry.
pay_ok: From Closed to Open.
enter: From Open to Closed.
public interface State {
void handleRequest();
}
public class ClosedState implements State {
public void handleRequest() {
// Logic for Closed State
}
}
public class OpenState implements State {
public void handleRequest() {
// Logic for Open State
}
}
public class Turnstile {
private State state;
public Turnstile() {
state = new ClosedState();
}
public void setState(State state) {
this.state = state;
}
public void handleRequest() {
state.handleRequest();
}
}public class ClosedState implements State {
public void handleRequest() {
// Transition to Open State
System.out.println("Payment OK. Gate opening.");
}
}
public class OpenState implements State {
public void handleRequest() {
// Transition to Closed State
System.out.println("Gate closing after entry.");
}
}Scenario: Payment failure at a closed turnstile.
Transition: Remains in Closed state.
New State: Processing.
Purpose: Handle payment processing before opening.
| State | Action | Next State |
|---|---|---|
| Closed | pay | Processing |
| Processing | pay_ok | Open |
| Processing | pay_fail | Closed |
| Open | enter | Closed |
Key Concept: Transition based on current state and event.
No Memory: State does not depend on the history of events.
Clear State Management: Each state and transition is distinct.
Reduced Complexity: Simplifies complex conditional logic.
Easier Maintenance: Adding new states or transitions is straightforward.
Events: Actions triggering state transitions (e.g., pay, enter).
Handling: Each state defines responses to events.
Objective: Understand the Null Object Pattern in Object-Oriented Programming
Key Focus: Usage of null, issues, and polymorphic solutions
Reference: Tony Hoare’s concept of null - A Billion Dollar Mistake
Null: Represents the concept of ‘nothingness’
Commonly used in languages to indicate the absence of a value
Example:
Issues with Null:
Can lead to null pointer exceptions
Forces conditional checks in code
nullnilNonenullptr or NULLEach represents the absence of a value, but implementation and handling may vary.
Two-Path Dilemma:
Path when variable is not null
Path when variable is null
Leads to increased complexity and conditional logic in code.
Objective: Avoid explicit null checks
Approach: Use polymorphism to handle ‘null’ behavior
Benefit: Simplifies code by avoiding conditionals
Definition: Ability of objects to take on many forms
How it helps:
Avoids conditionals
Simplifies code
Example:
Reduces Null Checks:
if (object != null) checksImproves Code Clarity:
Enhances Polymorphism:
Context: Use Null Object in Strategy Pattern
Scenario:
Different behaviors for an object
Include a ‘no behavior’ option
Scenario: Handling player movements in a game
Problem: Different states of movement, including immobility
Benefit: Allows dynamic change of behavior at runtime
Use Case: Changing player’s movement behavior based on game events
Scenario: Handling actions of UI elements like buttons
Problem: Some buttons may not always have an action
Simplifies Logic: No need to check for null commands
Consistency: Uniform handling of all UI elements
Extensibility: Easy to add new commands or change behavior
Scenario: Handling end of collections in iteration
Problem: Avoiding null checks for terminal elements