Design Pattern Flashcards
(21 cards)
What is a design pattern, and why are they used?
A design pattern is a reusable solution to a common software design problem. They improve code maintainability, readability, and scalability. Example: Singleton ensures a single instance of a class.
What is the Singleton pattern, and when is it used?
Singleton ensures a class has only one instance and provides global access. Used for logging or database connections. Example: class Singleton { static instance; constructor() { if (Singleton.instance) return Singleton.instance; Singleton.instance = this; } }
How do you implement the Singleton pattern in JavaScript?
```javascript
class DatabaseConnection {
static instance;
constructor() {
if (DatabaseConnection.instance) return DatabaseConnection.instance;
DatabaseConnection.instance = this;
this.connection = ‘db_connected’;
}
getConnection() { return this.connection; }
}
// Example: const db1 = new DatabaseConnection(); const db2 = new DatabaseConnection(); db1 === db2 // true
// Explanation: Returns the same instance, ensuring single connection (O(1)).
~~~
What is the Factory pattern, and what problem does it solve?
Factory creates objects without specifying the exact class. Solves complex object creation. Example: Creating different UI components based on type (button, input).
How do you implement the Factory pattern in JavaScript?
```javascript
class Button { render() { return ‘Button’; } }
class Input { render() { return ‘Input’; } }
class UIFactory {
static createComponent(type) {
if (type === ‘button’) return new Button();
if (type === ‘input’) return new Input();
}
}
// Example: UIFactory.createComponent(‘button’).render() // ‘Button’
// Explanation: Centralizes object creation logic (O(1)).
~~~
What is the Observer pattern, and where is it used?
Observer allows objects to subscribe to and receive updates from a subject. Used in event-driven systems like UI events or pub/sub. Example: DOM event listeners.
How do you implement the Observer pattern in JavaScript?
```javascript
class Subject {
constructor() { this.observers = []; }
subscribe(observer) { this.observers.push(observer); }
notify(data) { this.observers.forEach(observer => observer.update(data)); }
}
class Observer {
update(data) { console.log(Received: ${data}
); }
}
// Example: const subject = new Subject(); subject.subscribe(new Observer()); subject.notify(‘Event’) // logs ‘Received: Event’
// Explanation: Notifies all subscribers of state changes (O(n)).
~~~
What is the Strategy pattern, and when is it useful?
Strategy defines a family of algorithms, encapsulating them to be interchangeable. Useful for runtime behavior changes. Example: Different sorting algorithms in a search feature.
How do you implement the Strategy pattern in JavaScript?
```javascript
class QuickSort { sort(arr) { return arr.sort((a, b) => a - b); } }
class MergeSort { sort(arr) { /* Simplified */ return […arr].sort((a, b) => a - b); } }
class Sorter {
constructor(strategy) { this.strategy = strategy; }
sort(arr) { return this.strategy.sort(arr); }
}
// Example: const sorter = new Sorter(new QuickSort()); sorter.sort([3, 1, 2]) // [1, 2, 3]
// Explanation: Switches sorting logic dynamically (O(n log n) for sort).
~~~
What is the Decorator pattern, and what does it solve?
Decorator adds behavior to objects without modifying their code. Solves the need for flexible extensions. Example: Adding middleware in Express.
How do you implement the Decorator pattern in JavaScript?
```javascript
function Component(func) {
return (…args) => {
console.log(‘Decorated’);
return func(…args);
};
}
function sayHello(name) { return Hello, ${name}
; }
// Example: const decorated = Component(sayHello); decorated(‘Alice’) // logs ‘Decorated’, returns ‘Hello, Alice’
// Explanation: Wraps function to add behavior (O(1)).
~~~
What is the Adapter pattern, and when is it used?
Adapter makes incompatible interfaces work together. Used for legacy code integration. Example: Adapting an old API to a new system’s interface.
How do you implement the Adapter pattern in JavaScript?
```javascript
class OldAPI { oldRequest() { return ‘Old data’; } }
class NewAPI { request() { return ‘New data’; } }
class Adapter {
constructor(oldAPI) { this.oldAPI = oldAPI; }
request() { return this.oldAPI.oldRequest(); }
}
// Example: const adapter = new Adapter(new OldAPI()); adapter.request() // ‘Old data’
// Explanation: Converts old interface to new (O(1)).
~~~
What is the Command pattern, and where is it useful?
Command encapsulates a request as an object, allowing parameterization and queuing. Useful for undo/redo operations. Example: Editor save commands.
What is the Facade pattern, and what problem does it solve?
Facade provides a simplified interface to a complex subsystem. Solves complexity in libraries. Example: jQuery simplifies DOM manipulation.
How do you implement the Facade pattern in JavaScript?
```javascript
class SubsystemA { operationA() { return ‘A’; } }
class SubsystemB { operationB() { return ‘B’; } }
class Facade {
constructor() { this.a = new SubsystemA(); this.b = new SubsystemB(); }
simpleOperation() { return this.a.operationA() + this.b.operationB(); }
}
// Example: new Facade().simpleOperation() // ‘AB’
// Explanation: Simplifies subsystem access (O(1)).
~~~
What is the Prototype pattern, and how is it used in JavaScript?
Prototype creates objects by cloning a prototype. JavaScript uses it natively via prototypes. Example: Object.create({ x: 1 })
clones an object.
What is the Mediator pattern, and when is it used?
Mediator centralizes communication between objects to reduce coupling. Used in event hubs. Example: Chatroom where users communicate via a central mediator.
What is the Iterator pattern, and how is it implemented in JavaScript?
Iterator provides sequential access to a collection. JavaScript uses for...of
with iterables. Example: const arr = [1, 2]; for (let x of arr) console.log(x);
.
What is the Composite pattern, and where is it used?
Composite treats individual objects and compositions uniformly. Used in tree structures like DOM or UI components. Example: React component hierarchies.
How do you apply design patterns in a full-stack app?
Use Singleton for database connections, Factory for creating API clients, Observer for real-time updates (e.g., WebSockets), and Strategy for interchangeable algorithms (e.g., authentication methods).