0% found this document useful (0 votes)
5 views11 pages

Design_Patterns_Study_Sheet-1

The document outlines various design patterns including Observer, Decorator, Factory Method, Abstract Factory, Singleton, Command, Adapter, Facade, and Template Method, detailing their purposes, structures, pros, and cons. It emphasizes key concepts such as loose coupling, the Open-Closed Principle, and the importance of composition over inheritance. Additionally, it highlights unique content related to concurrency in the Singleton pattern and deeper comparisons between Factory Method and Abstract Factory, as well as implementation notes for the Decorator pattern.

Uploaded by

eray.denkci
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Design_Patterns_Study_Sheet-1

The document outlines various design patterns including Observer, Decorator, Factory Method, Abstract Factory, Singleton, Command, Adapter, Facade, and Template Method, detailing their purposes, structures, pros, and cons. It emphasizes key concepts such as loose coupling, the Open-Closed Principle, and the importance of composition over inheritance. Additionally, it highlights unique content related to concurrency in the Singleton pattern and deeper comparisons between Factory Method and Abstract Factory, as well as implementation notes for the Decorator pattern.

Uploaded by

eray.denkci
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Design Patterns Study Sheet

Observer Pattern

Type: Behavioral Design Pattern

Purpose: Defines a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.

Key Concept: Publish-subscribe mechanism where observers register with a subject and
are notified of state changes.

When to Use:

• When an object’s state change should trigger updates to other objects.

• When tight coupling between objects should be avoided.

Key Principles and Structure:

• Subject: Maintains a list of observers and provides methods to attach, detach, and
notify them.

• Observer: Defines an interface for receiving update notifications from the subject.

• ConcreteSubject: Stores the state of interest to ConcreteObservers and notifies


them when the state changes.

• ConcreteObserver: Implements the Observer interface and maintains a reference


to the ConcreteSubject to stay synchronized.

Pros:

• Promotes loose coupling between subject and observers.

• Supports broadcast communication.

Cons:

• Potential for memory leaks if observers are not properly deregistered.

• Complex dependency chain can make debugging difficult.

Decorator Pattern

Type: Structural Design Pattern


Purpose: Allows additional responsibilities to be dynamically attached to an object without
modifying its structure.

Key Concept: Objects are wrapped with other objects (decorators) that add behavior
before or after delegating calls to the wrapped object.

When to Use:

• When you need to add behavior to objects at runtime.

• When subclassing would create an explosion of subclasses for every combination of


features.

Key Principles and Structure:

• Component: Defines the interface for objects that can have additional
responsibilities.

• ConcreteComponent: The original object that will be decorated.

• Decorator: Implements the Component interface and has a reference to a


Component.

• ConcreteDecorator: Adds new behavior by overriding methods and calling the


wrapped object's methods.

Pros:

• More flexible than static inheritance.

• Supports the Open-Closed Principle.

• Enables dynamic composition of behavior.

Cons:

• Many similar small objects can complicate debugging.

• Identity comparison between decorated and undecorated objects becomes


ambiguous.

Factory Method Pattern

Type: Creational Design Pattern

Purpose: Defines an interface for creating an object but allows subclasses to alter the type
of objects that will be created.
Key Concept: Creation is delegated to subclasses by overriding the factory method.

When to Use:

• When a class can’t anticipate the class of objects it must create.

• When subclasses should specify the objects to be created.

Key Principles and Structure:

• Product: Interface or abstract class for products.

• ConcreteProduct: Implements the Product interface.

• Creator: Declares the factory method.

• ConcreteCreator: Overrides the factory method to return a ConcreteProduct.

Pros:

• Eliminates binding of application-specific classes to code.

• Provides hooks for subclassing.

Cons:

• Might lead to many subclasses.

• Requires understanding of inheritance and polymorphism.

Abstract Factory Pattern

Type: Creational Design Pattern

Purpose: Provides an interface for creating families of related or dependent objects


without specifying their concrete classes.

Key Concept: Uses composition to delegate object creation to multiple factory methods
grouped in a single factory interface.

When to Use:

• When the system should be independent of how its products are created.

• When families of related products are used together.

Key Principles and Structure:

• AbstractFactory: Declares an interface for creating abstract product objects.


• ConcreteFactory: Implements the creation methods of AbstractFactory.

• AbstractProduct: Declares an interface for a product.

• ConcreteProduct: Implements the AbstractProduct interface.

Pros:

• Ensures consistency among products.

• Isolates concrete class implementations.

Cons:

• Complexity increases with number of product families.

• Difficult to add new product types.

Singleton Pattern

Type: Creational Design Pattern

Purpose: Ensures a class has only one instance and provides a global point of access to it.

Key Concept: The class is responsible for controlling its own instance through a private
constructor and static access method.

When to Use:

• When exactly one instance of a class is required (e.g., logging, configuration).

• When the instance should be globally accessible.

Key Principles and Structure:

• Private Constructor: Prevents direct instantiation.

• Static Instance Variable: Holds the single instance.

• Static getInstance() Method: Returns the instance, creates it if it doesn’t exist.

• Thread-Safe Implementation: Optional, with synchronized or eager initialization.

Pros:

• Controlled access to sole instance.

• Reduces memory footprint.


Cons:

• Can introduce global state.

• Difficult to test due to tight coupling.

• Subclassing is difficult.

Command Pattern

Type: Behavioral Design Pattern

Purpose: Encapsulates a request as an object, allowing the request to be parameterized,


queued, logged, and undone.

Key Concept: A command object encapsulates an action and its receiver, exposing an
execute() method to trigger the action, and optionally undo() for reversibility.

When to Use:

• To implement undo/redo functionality.

• When actions need to be queued or executed later.

• To decouple UI elements from the operations they trigger.

• To store and replay operations (macro recording).

Key Principles and Structure:

• Command Interface: Declares execute() (and optionally undo()).

• ConcreteCommand: Implements the Command interface; holds a reference to the


Receiver and defines the actual action.

• Receiver: Knows how to perform the operation associated with the command.

• Invoker: Stores command objects and triggers them when needed (e.g., a button
click).

• Client: Creates the command and binds it to a Receiver; assigns command to an


Invoker.

Pros:

• Promotes loose coupling between sender and receiver.

• Enables implementation of undo/redo.


• Allows requests to be queued, logged, and dynamically configured.

• Supports macro commands (grouped actions).

Cons:

• Requires creating many command classes.

• Adds complexity due to additional abstractions.

Adapter Pattern

Type: Structural Design Pattern

Purpose: Converts the interface of a class into another interface clients expect. Enables
incompatible interfaces to work together.

Key Concept: Acts as a translator between a client and an incompatible class (adaptee),
wrapping the adaptee’s methods in the target interface.

When to Use:

• When you want to reuse an existing class, but its interface is incompatible.

• When integrating third-party code or legacy components with different interfaces.

• When you need to apply an expected interface onto an existing class.

Key Principles and Structure:

• Target: Defines the expected interface that clients use.

• Adaptee: The existing class with an incompatible interface.

• Adapter: Implements the target interface and delegates calls to the adaptee.

• Client: Uses the adapter to interact with the adaptee indirectly.

Pros:

• Promotes reusability of existing functionality without modification.

• Decouples client code from third-party or legacy components.

• Adheres to Interface Segregation and Single Responsibility Principles.

Cons:

• May require writing extensive adapter code for large interfaces.


• Adds an extra layer of indirection.

Facade Pattern

Type: Structural Design Pattern

Purpose: Provides a unified, simplified interface to a complex subsystem.

Key Concept: Acts as a “front-facing” interface that delegates requests to appropriate


objects in the subsystem.

When to Use:

• When clients need a simplified interface to a complex system.

• To minimize client dependency on subsystem internals.

• To layer an application or separate concerns clearly.

Key Principles and Structure:

• Facade: Provides the simplified interface and delegates requests.

• Subsystem Classes: Perform the actual work; unaware of the Facade.

• Client: Uses only the Facade interface.

Pros:

• Simplifies usage of complex systems.

• Reduces coupling and compilation dependencies.

• Promotes the Principle of Least Knowledge.

Cons:

• May hide powerful features of the subsystem.

• Facade can become a “god object” if it grows too large.

Template Method Pattern

Type: Behavioral Design Pattern


Purpose: Defines the skeleton of an algorithm in a method, deferring some steps to
subclasses. Allows subclasses to redefine certain steps of an algorithm without changing its
structure.

Key Concept: A template method contains fixed parts of an algorithm, calling abstract or
hook methods for customizable behavior.

When to Use:

• When you have multiple classes performing similar steps in the same order.

• To maximize code reuse and maintain algorithm control in a superclass.

• When parts of an algorithm should be implemented or optionally overridden by


subclasses.

Key Principles and Structure:

• AbstractClass: Defines the template method as final and provides base


implementation.

• Template Method: Contains a fixed algorithm with calls to abstract and/or hook
methods.

• Primitive Operations: Abstract methods that subclasses must implement.

• Hook Methods: Optional methods that subclasses can override to extend behavior.

• ConcreteClass: Implements the abstract methods and optionally overrides hooks.

Pros:

• Promotes code reuse by centralizing algorithm logic.

• Supports consistent algorithm structure with customizable steps.

• Reduces duplication and encourages DRY (Don’t Repeat Yourself).

Cons:

• Inflexible if steps need to change order.

• Requires inheritance, which limits composition-based flexibility.

Important Concepts and Principles


• Loose Coupling: Objects are designed to interact with each other with minimal
knowledge of their internal workings. This makes the system easier to maintain,
extend, and test, because changes in one module are less likely to affect others.

• Open-Closed Principle (OCP): A module or class should be open for extension but
closed for modification. In practice, this means adding new features should be done
by adding new code (like subclasses or decorators), not modifying existing code.

• Composition vs. Inheritance: Composition means building complex behavior by


combining objects, while inheritance builds relationships via class hierarchies.
Composition is preferred when flexibility and runtime behavior changes are needed.

• Global State: Global state refers to data accessible from many parts of the system.
While convenient, it can cause hidden dependencies, reduce modularity, and make
debugging and testing difficult.

• Thread-Safety: A thread-safe class functions correctly when used by multiple


threads simultaneously. In patterns like Singleton, this prevents multiple instances
from being created in multithreaded environments.

• Dependency Inversion Principle: High-level modules should not depend on low-


level modules. Both should depend on abstractions (interfaces). Patterns like
Factory and Abstract Factory help enforce this principle by hiding concrete class
dependencies.

• Dynamic Behavior Attachment: The ability to add behavior to an object at runtime


(e.g., Decorator Pattern). This provides more flexibility compared to static
inheritance.

• Publish-Subscribe Mechanism: A messaging system where publishers emit


messages/events without knowing the subscribers. The Observer Pattern is a classic
example, allowing a one-to-many relationship.

• MacroCommand: A command that contains a list of other commands. Useful in the


Command Pattern for executing sequences of operations as a single action (e.g.,
“Party Mode” in a smart home system).

• Null Object: A design pattern that provides a default object with neutral behavior in
place of a null reference. It prevents null pointer exceptions and simplifies code that
relies on optional behavior.

• Interface Segregation Principle: Clients should not be forced to depend on


interfaces they do not use. The Adapter Pattern helps enforce this by exposing only
the relevant methods to the client.
• Principle of Least Knowledge (Law of Demeter): An object should only
communicate with its immediate collaborators. This reduces the interdependence of
modules, improving maintainability and reducing unintended side effects.

• Hook Method: A method defined in an abstract class with a default or empty


implementation that can be optionally overridden by subclasses to customize
behavior. Used in the Template Method Pattern.

• Hollywood Principle: “Don’t call us, we’ll call you.” Higher-level components
control the flow of the algorithm and invoke lower-level components when needed.
This is central to the Template Method Pattern.

Unique & Valuable Content Only in Özet.pdf

Singleton Pattern

• Multithreading Details:

o Thorough explanation of lazy vs eager instantiation.

o Discussion of synchronized method and its performance cost.

o Explanation of Double-Checked Locking (DCL) and related concerns (e.g.,


volatile keyword).

• Advantages:

o Explicit discussion on memory savings, controlled access, and use cases.

• Caveats:

o Mentions risks like global state, difficulty in testing, subclassing limitations,


and classloader issues.

None of this level of concurrency-related detail is present in the Study Sheet.

Factory Method vs Abstract Factory

• Clear comparison:

o Factory Method uses inheritance, creates a single product.

o Abstract Factory uses composition, creates families of related products.

• Includes Simple Factory:

o Explains it’s not a formal GoF pattern but a commonly used idiom.
• Design Principles Connection:

o Discusses how these patterns support Dependency Inversion and


interface-based design.

Study Sheet doesn't offer this depth of comparison or design principle integration.

Decorator Pattern

• Deeper structure explanation:

o Explains recursive composition and transparent wrapping.

• Implementation Notes:

o Emphasizes interface conformance for decorators.

o Differentiates decorator (external behavior) from strategy (internal logic).

• Real-world examples:

o Java I/O streams, GUI features, and Starbuzz Coffee example (adding
condiments dynamically).

Study Sheet lacks these detailed examples and comparisons.

General Conceptual Foundations

• “The Problem with new” section:

o Explains how using new directly couples code to concrete classes and breaks
encapsulation.

• Creational Pattern Philosophy:

o Discusses the broader goal of hiding construction details and enabling


flexibility and maintainability.

These conceptual insights are not in the Study Sheet.

You might also like