Sobes.tech
Junior

What design patterns do you know?

sobes.tech AI

Answer from AI

Creational:

  • Singleton: Ensures a class has only one instance and provides a global point of access to it.
  • Factory Method: Defines an interface for creating an object but allows subclasses to decide which class to instantiate.
  • Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  • Builder: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
  • Prototype: Creates new objects by copying an existing object (prototype), rather than creating new instances from scratch.

Structural:

  • Adapter: Converts the interface of a class into another interface clients expect. Allows classes with incompatible interfaces to work together.
  • Bridge: Decouples an abstraction from its implementation, so they can vary independently.
  • Composite: Composes objects into tree structures to represent hierarchies. Allows clients to treat individual objects and compositions uniformly.
  • Decorator: Adds responsibilities to objects dynamically by wrapping them in decorator objects.
  • Facade: Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use.
  • Flyweight: Uses sharing to support large numbers of fine-grained objects efficiently.
  • Proxy: Provides a surrogate or placeholder for another object to control access to it.

Behavioral:

  • Chain of Responsibility: Passes a request along a chain of handlers. Each handler decides whether to process the request or pass it on.
  • Command: Encapsulates a request as an object, allowing parameterization of clients with different requests, queuing of requests, and logging.
  • Interpreter: Defines a grammatical representation for a language and an interpreter to interpret sentences in the language.
  • Iterator: Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Mediator: Defines an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly.
  • Memento: Captures and externalizes an object's internal state so that the object can be restored to this state later.
  • Observer: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • State: Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • Strategy: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Lets the algorithm vary independently from clients that use it.
  • Template Method: Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing its structure.
  • Visitor: Represents an operation to be performed on the elements of an object structure. Lets you define a new operation without changing the classes of the elements.

In iOS development, also common are:

  • Model-View-Controller (MVC): Architectural pattern dividing an application into three components: Model (data and business logic), View (user interface), and Controller (mediates between Model and View).
  • Delegate: Pattern that allows one object to act on behalf of or in coordination with another.
  • Observer (NotificationCenter): A notification dispatch system allowing objects to receive messages without direct coupling.
  • Target-Action: Mechanism for sending messages from control elements (like buttons) to a target object.
  • Coordinator: Pattern for managing navigation flows in an app, separating navigation logic from view controllers.
  • Dependency Injection: Pattern where dependencies are injected into an object from outside, rather than the object creating them itself.
// Singleton example
class SettingsManager {
    static let shared = SettingsManager() // Single instance

    private init() {
        // Private initializer to prevent external creation
    }

    var appVersion: String {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
    }
}

// Usage
let settings = SettingsManager.shared
print("App Version: \(settings.appVersion)")
// Delegate example (simple)
protocol ButtonDelegate: AnyObject {
    func buttonWasTapped(_ button: UIButton)
}

class MyButton: UIButton {
    weak var delegate: ButtonDelegate? // Delegate property

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        delegate?.buttonWasTapped(self) // Call delegate method
    }
}

class ViewController: UIViewController, ButtonDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        let myButton = MyButton(frame: CGRect(x: 50, y: 50, width: 100, height: 40))
        myButton.setTitle("Tap Me", for: .normal)
        myButton.backgroundColor = .blue
        myButton.delegate = self // Set delegate
        view.addSubview(myButton)
    }

    func buttonWasTapped(_ button: UIButton) {
        print("Button was tapped in ViewController")
    }
}
What design patterns do you know? — iOS - sobes.tech