Quiz 2
Registry Synced

🎨 Design Patterns

314 words
2 min read

Reading compass

Now · 1. 🎯 Learning Objectives

🎨 Design Patterns

1. 🎯 Learning Objectives

  • Implement Singleton, Factory, Observer, Strategy patterns
  • Explain the MVC architectural pattern
  • Choose appropriate pattern for a given design problem

2. 📖 Core Content

3.1 Singleton

Ensures a class has exactly one instance and provides global access.
java
public class DatabaseConnection {
    private static DatabaseConnection instance;
    private DatabaseConnection() {}
    public static DatabaseConnection getInstance() {
        if (instance == null) instance = new DatabaseConnection();
        return instance;
    }
}

3.2 Factory Method

Creates objects without specifying the exact class.
java
public interface Shape { void draw(); }
public class Circle implements Shape { ... }
public class Square implements Shape { ... }
public class ShapeFactory {
    public Shape createShape(String type) {
        if (type.equals("circle")) return new Circle();
        else if (type.equals("square")) return new Square();
        return null;
    }
}

3.3 Observer

Defines one-to-many dependency — when one object changes state, all dependents are notified.
java
public interface Observer { void update(String data); }
public class Subject {
    List<Observer> observers = new ArrayList<>();
    public void attach(Observer o) { observers.add(o); }
    public void notifyObservers() {
        for (Observer o : observers) o.update(data);
    }
}

3.4 Strategy

Defines a family of algorithms, encapsulates each, and makes them interchangeable.
java
public interface SortStrategy { void sort(int[] data); }
public class BubbleSort implements SortStrategy { ... }
public class QuickSort implements SortStrategy { ... }
public class Sorter {
    private SortStrategy strategy;
    public void setStrategy(SortStrategy s) { this.strategy = s; }
    public void sort(int[] data) { strategy.sort(data); }
}

3.5 MVC (Model-View-Controller)

ComponentResponsibility
ModelData and business logic
ViewUser interface (display)
ControllerHandles input, updates model and view

4. 📝 Practice Questions

Q1: You need to ensure exactly one configuration manager object exists. Which pattern?
Answer: Singleton. The ConfigurationManager class should have a private constructor and a static getInstance() method. Join Discord PreviousSOLID PrinciplesNextUML Diagrams
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.