[25] Design patterns Flashcards

(44 cards)

1
Q

What is the Singleton pattern and give an iOS example?

A

Ensures only one instance of a class exists. Example: UIApplication.shared, UserDefaults.standard.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the downside of using Singleton in iOS?

A

Global state, makes testing harder, can cause hidden dependencies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Code sample of singleton pattern

A
final class Singleton {
    // 1. Shared static instance (lazy + thread-safe)
    static let shared = Singleton()
    
    // 2. Private initializer prevents external initialization
    private init() {}
    
    // Example method
    func doSomething() {
        print("Singleton instance is working.")
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the Observer pattern and give an iOS example?

A

Defines a one-to-many dependency so observers are notified of changes. Example: NotificationCenter, KVO, Combine publishers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Sample code for notification Center

A
import Foundation

// Sender
class Poster {
    func postMessage() {
        NotificationCenter.default.post(name: .myNotification, object: nil)
    }
}

// Receiver
class Observer {
    init() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleNotification),
            name: .myNotification,
            object: nil
        )
    }
    
    @objc private func handleNotification() {
        print("Notification received!")
    }
}

// Usage
extension Notification.Name {
    static let myNotification = Notification.Name("MyNotification")
}

let observer = Observer()
let poster = Poster()
poster.postMessage()  // prints: Notification received!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the Delegation pattern and how is it used in iOS?

A

One object delegates responsibility to another via a protocol. Example: UITableViewDelegate, UITextFieldDelegate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the Factory Method pattern and give an iOS example?

A

Provides an interface for creating objects but lets subclasses decide the type. Example: UIButton(type: .system).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the Adapter pattern and give an iOS example?

A

Converts one interface into another expected by clients. Example: Using NSFetchedResultsController to adapt Core Data results for UITableView.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is MVC in iOS architecture?

A

Model-View-Controller: Apple’s classic architecture, but can lead to ‘Massive View Controller’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is MVVM and how does it improve over MVC?

A

Model-View-ViewModel separates presentation logic into the ViewModel, reducing controller size. Common with Combine/SwiftUI.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the Strategy pattern and give an iOS example?

A

Defines a family of interchangeable algorithms. Example: Sorting arrays with different closures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the Command pattern and give an iOS example?

A

Encapsulates an action as an object. Example: NSUndoManager commands for undo/redo.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the Facade pattern and give an iOS example?

A

Provides a simplified interface to a complex subsystem. Example: URLSession as a facade over CFNetwork.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the Iterator pattern and give an iOS example?

A

Provides a way to access elements of a collection sequentially without exposing internal representation. Example: Swift Sequence and IteratorProtocol.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the Composite pattern and give an iOS example?

A

Treats individual objects and compositions uniformly. Example: UIView containing subviews in UIKit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Why is Singleton commonly used in iOS frameworks?

A

To provide global shared resources like UIApplication, FileManager, UserDefaults without multiple instances.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How can you make a Singleton thread-safe in Swift?

A

By using a static constant which is lazily initialized and guaranteed to be thread-safe in Swift.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the difference between NotificationCenter and KVO?

A

NotificationCenter broadcasts to many observers; KVO observes property changes on specific objects.

19
Q

How is the Observer pattern used in SwiftUI?

A

Via @Published properties and ObservableObject, which notify SwiftUI views automatically.

20
Q

Why is Delegation preferred over NotificationCenter in UIKit?

A

Delegation is one-to-one and enforces compile-time contracts via protocols, making it safer.

21
Q

How does Delegation reduce coupling?

A

By defining behavior in a protocol, the delegate class can change without modifying the delegating class.

22
Q

What is the advantage of Factory Method in Swift?

A

It encapsulates object creation, makes code more flexible and testable, avoids spreading init details.

23
Q

Give an example of Factory Method in Foundation or UIKit.

A

URLRequest(url:) creates a request; UIButton(type:) creates a button with style.

24
Q

When would you use the Adapter pattern in iOS?

A

When you want to integrate a legacy API with a new interface, e.g., adapting old Objective-C APIs for SwiftUI.

25
What is the difference between Adapter and Facade?
Adapter converts one interface to another; Facade simplifies a subsystem with a unified API.
26
Why can MVC lead to 'Massive View Controller' in iOS?
Because UIViewController often ends up handling UI, data logic, and navigation, mixing responsibilities.
27
How does MVVM help testing in iOS?
Business logic in ViewModel can be tested independently without UI framework dependencies.
28
What is the benefit of Strategy pattern in Swift?
It allows changing algorithms at runtime by passing different closures or strategy objects.
29
Give an iOS example where Strategy is used implicitly.
Sorting collections with custom closures, e.g., sorted(by:).
30
How does Command pattern support undo operations?
Each action is encapsulated as a command object that can be stored and reversed by calling undo().
31
Give an example of Command pattern in UIKit.
UIKeyCommand and UICommand encapsulate user actions in menus and keyboard shortcuts.
32
Why is URLSession a Facade?
It provides a simple API for network tasks while hiding lower-level CFNetwork complexities.
33
How does Swift implement Iterator pattern?
Through Sequence and IteratorProtocol; for-in loops use them under the hood.
34
Why is Iterator useful?
It allows sequential access to collections without exposing internal details like array indices.
35
Why is the UIView hierarchy an example of Composite?
Both UIView and its subviews conform to the same interface, allowing recursive composition.
36
How does Composite pattern simplify UI code?
It lets you treat individual views and groups of views uniformly, e.g., applying constraints or transforms.
37
What is the Prototype pattern and give an iOS example?
Creates new objects by cloning existing ones. Example: NSCopying protocol.
38
What is the Builder pattern and give an iOS example?
Separates object construction from representation. Example: URLComponents building a URL.
39
What is the Chain of Responsibility pattern and give an iOS example?
Passes a request along a chain of handlers. Example: UIResponder chain for touch events.
40
What is the Memento pattern and give an iOS example?
Captures and restores an object's state. Example: State restoration APIs in UIKit.
41
What is the Flyweight pattern and give an iOS example?
Minimizes memory by sharing objects. Example: Reusing cell objects in UITableView with reuseIdentifier.
42
What is the Mediator pattern and give an iOS example?
Defines an object that centralizes communication. Example: UICollectionView mediates between cells, layout, and data source.
43
What is the Template Method pattern and give an iOS example?
Defines the skeleton of an algorithm, deferring steps to subclasses. Example: UIView.draw(_:) where subclasses override drawing behavior.
44