Neural Sync Active
🎨 Design Patterns
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.
javapublic 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.
javapublic 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.
javapublic 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.
javapublic 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)
| Component | Responsibility |
|---|---|
| Model | Data and business logic |
| View | User interface (display) |
| Controller | Handles 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