|
| 1 | +# Design Patterns Guide |
| 2 | + |
| 3 | +This guide provides an overview of the design patterns implemented in DesignAlgorithmsKit, their use cases, and examples. |
| 4 | + |
| 5 | +## Creational Patterns |
| 6 | + |
| 7 | +### Singleton Pattern |
| 8 | + |
| 9 | +Ensures a class has only one instance and provides global access to it. |
| 10 | + |
| 11 | +**Implementation**: `ThreadSafeSingleton`, `ActorSingleton` |
| 12 | + |
| 13 | +**Use Cases**: |
| 14 | +- Configuration managers |
| 15 | +- Logging systems |
| 16 | +- Database connections |
| 17 | +- Cache managers |
| 18 | + |
| 19 | +**Example**: |
| 20 | +```swift |
| 21 | +class AppConfig: ThreadSafeSingleton { |
| 22 | + private override init() { |
| 23 | + super.init() |
| 24 | + // Initialize configuration |
| 25 | + } |
| 26 | + |
| 27 | + override class func createShared() -> Self { |
| 28 | + return Self() |
| 29 | + } |
| 30 | + |
| 31 | + var apiKey: String = "" |
| 32 | +} |
| 33 | + |
| 34 | +// Usage |
| 35 | +AppConfig.shared.apiKey = "your-api-key" |
| 36 | +``` |
| 37 | + |
| 38 | +### Factory Pattern |
| 39 | + |
| 40 | +Creates objects without specifying the exact class of object that will be created. |
| 41 | + |
| 42 | +**Implementation**: `ObjectFactory` |
| 43 | + |
| 44 | +**Use Cases**: |
| 45 | +- Creating objects based on configuration |
| 46 | +- Dependency injection |
| 47 | +- Plugin systems |
| 48 | + |
| 49 | +**Example**: |
| 50 | +```swift |
| 51 | +class UserFactory: ObjectFactory { |
| 52 | + static func create(type: String, configuration: [String: Any]) throws -> Any { |
| 53 | + switch type { |
| 54 | + case "admin": |
| 55 | + return AdminUser(configuration: configuration) |
| 56 | + case "regular": |
| 57 | + return RegularUser(configuration: configuration) |
| 58 | + default: |
| 59 | + throw FactoryError.unknownType(type) |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +### Builder Pattern |
| 66 | + |
| 67 | +Constructs complex objects step by step with a fluent API. |
| 68 | + |
| 69 | +**Implementation**: `BaseBuilder` |
| 70 | + |
| 71 | +**Use Cases**: |
| 72 | +- Creating complex objects with many optional parameters |
| 73 | +- Immutable object construction |
| 74 | +- Configuration objects |
| 75 | + |
| 76 | +**Example**: |
| 77 | +```swift |
| 78 | +class HTTPRequestBuilder: BaseBuilder<HTTPRequest> { |
| 79 | + private var url: URL? |
| 80 | + private var method: String = "GET" |
| 81 | + private var headers: [String: String] = [:] |
| 82 | + |
| 83 | + func setURL(_ url: URL) -> Self { |
| 84 | + self.url = url |
| 85 | + return self |
| 86 | + } |
| 87 | + |
| 88 | + func setMethod(_ method: String) -> Self { |
| 89 | + self.method = method |
| 90 | + return self |
| 91 | + } |
| 92 | + |
| 93 | + func addHeader(_ key: String, value: String) -> Self { |
| 94 | + self.headers[key] = value |
| 95 | + return self |
| 96 | + } |
| 97 | + |
| 98 | + override func build() throws -> HTTPRequest { |
| 99 | + guard let url = url else { |
| 100 | + throw BuilderError.missingRequiredProperty("url") |
| 101 | + } |
| 102 | + return HTTPRequest(url: url, method: method, headers: headers) |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +// Usage |
| 107 | +let request = try HTTPRequestBuilder() |
| 108 | + .setURL(URL(string: "https://api.example.com")!) |
| 109 | + .setMethod("POST") |
| 110 | + .addHeader("Content-Type", value: "application/json") |
| 111 | + .build() |
| 112 | +``` |
| 113 | + |
| 114 | +## Structural Patterns |
| 115 | + |
| 116 | +### Adapter Pattern |
| 117 | + |
| 118 | +Allows objects with incompatible interfaces to work together. |
| 119 | + |
| 120 | +**Implementation**: `Adapter` protocol |
| 121 | + |
| 122 | +**Use Cases**: |
| 123 | +- Integrating third-party libraries |
| 124 | +- Legacy code integration |
| 125 | +- Interface compatibility |
| 126 | + |
| 127 | +**Example**: |
| 128 | +```swift |
| 129 | +protocol PaymentProcessor { |
| 130 | + func processPayment(amount: Double) -> Bool |
| 131 | +} |
| 132 | + |
| 133 | +class LegacyPaymentSystem { |
| 134 | + func pay(amount: Double) -> Bool { |
| 135 | + // Legacy implementation |
| 136 | + return true |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +class LegacyPaymentAdapter: Adapter { |
| 141 | + typealias Adaptee = LegacyPaymentSystem |
| 142 | + typealias Target = PaymentProcessor |
| 143 | + |
| 144 | + private let adaptee: Adaptee |
| 145 | + |
| 146 | + init(adaptee: Adaptee) { |
| 147 | + self.adaptee = adaptee |
| 148 | + } |
| 149 | + |
| 150 | + func adapt() -> Target { |
| 151 | + return AdaptedPaymentProcessor(adaptee: adaptee) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +class AdaptedPaymentProcessor: PaymentProcessor { |
| 156 | + private let adaptee: LegacyPaymentSystem |
| 157 | + |
| 158 | + init(adaptee: LegacyPaymentSystem) { |
| 159 | + self.adaptee = adaptee |
| 160 | + } |
| 161 | + |
| 162 | + func processPayment(amount: Double) -> Bool { |
| 163 | + return adaptee.pay(amount: amount) |
| 164 | + } |
| 165 | +} |
| 166 | +``` |
| 167 | + |
| 168 | +### Facade Pattern |
| 169 | + |
| 170 | +Provides a simplified interface to a complex subsystem. |
| 171 | + |
| 172 | +**Implementation**: `Facade` protocol |
| 173 | + |
| 174 | +**Use Cases**: |
| 175 | +- Simplifying complex APIs |
| 176 | +- Hiding implementation details |
| 177 | +- Providing a unified interface |
| 178 | + |
| 179 | +**Example**: |
| 180 | +```swift |
| 181 | +class MediaPlayerFacade: Facade { |
| 182 | + private let audioPlayer = AudioPlayer() |
| 183 | + private let videoPlayer = VideoPlayer() |
| 184 | + private let subtitleManager = SubtitleManager() |
| 185 | + |
| 186 | + func play(media: Media) { |
| 187 | + switch media.type { |
| 188 | + case .audio: |
| 189 | + audioPlayer.play(media.url) |
| 190 | + case .video: |
| 191 | + videoPlayer.play(media.url) |
| 192 | + subtitleManager.load(media.subtitleURL) |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + func stop() { |
| 197 | + audioPlayer.stop() |
| 198 | + videoPlayer.stop() |
| 199 | + subtitleManager.hide() |
| 200 | + } |
| 201 | +} |
| 202 | +``` |
| 203 | + |
| 204 | +## Behavioral Patterns |
| 205 | + |
| 206 | +### Strategy Pattern |
| 207 | + |
| 208 | +Defines a family of algorithms, encapsulates each one, and makes them interchangeable. |
| 209 | + |
| 210 | +**Implementation**: `Strategy` protocol, `StrategyContext` |
| 211 | + |
| 212 | +**Use Cases**: |
| 213 | +- Algorithm selection at runtime |
| 214 | +- Different sorting strategies |
| 215 | +- Payment processing methods |
| 216 | + |
| 217 | +**Example**: |
| 218 | +```swift |
| 219 | +struct QuickSortStrategy: Strategy { |
| 220 | + func execute<T: Comparable>(_ input: [T]) -> [T] { |
| 221 | + // Quick sort implementation |
| 222 | + return input.sorted() |
| 223 | + } |
| 224 | +} |
| 225 | + |
| 226 | +struct MergeSortStrategy: Strategy { |
| 227 | + func execute<T: Comparable>(_ input: [T]) -> [T] { |
| 228 | + // Merge sort implementation |
| 229 | + return input.sorted() |
| 230 | + } |
| 231 | +} |
| 232 | + |
| 233 | +// Usage |
| 234 | +let context = StrategyContext(strategy: QuickSortStrategy()) |
| 235 | +let sorted = context.execute([3, 1, 4, 1, 5, 9, 2, 6]) |
| 236 | +``` |
| 237 | + |
| 238 | +### Observer Pattern |
| 239 | + |
| 240 | +Defines a one-to-many dependency between objects so that when one object changes state, all dependents are notified. |
| 241 | + |
| 242 | +**Implementation**: `Observer` protocol, `Observable` protocol, `BaseObservable` |
| 243 | + |
| 244 | +**Use Cases**: |
| 245 | +- Event handling systems |
| 246 | +- Model-View architectures |
| 247 | +- Notification systems |
| 248 | + |
| 249 | +**Example**: |
| 250 | +```swift |
| 251 | +class DataModel: BaseObservable { |
| 252 | + private var value: String = "" { |
| 253 | + didSet { |
| 254 | + notifyObservers(event: value) |
| 255 | + } |
| 256 | + } |
| 257 | + |
| 258 | + func updateValue(_ newValue: String) { |
| 259 | + value = newValue |
| 260 | + } |
| 261 | +} |
| 262 | + |
| 263 | +class ViewController: Observer { |
| 264 | + func didReceiveNotification(from observable: any Observable, event: Any) { |
| 265 | + if let value = event as? String { |
| 266 | + print("Value updated to: \(value)") |
| 267 | + } |
| 268 | + } |
| 269 | +} |
| 270 | + |
| 271 | +// Usage |
| 272 | +let model = DataModel() |
| 273 | +let viewController = ViewController() |
| 274 | +model.addObserver(viewController) |
| 275 | +model.updateValue("Hello, World!") |
| 276 | +``` |
| 277 | + |
| 278 | +## Modern Patterns |
| 279 | + |
| 280 | +### Registry Pattern |
| 281 | + |
| 282 | +Provides centralized type registration and discovery. |
| 283 | + |
| 284 | +**Implementation**: `TypeRegistry` |
| 285 | + |
| 286 | +**Use Cases**: |
| 287 | +- Plugin systems |
| 288 | +- Dependency injection containers |
| 289 | +- Type factories |
| 290 | + |
| 291 | +**Example**: |
| 292 | +```swift |
| 293 | +// Register types |
| 294 | +TypeRegistry.shared.register(UserService.self, forKey: "userService") |
| 295 | +TypeRegistry.shared.register(ProductService.self, forKey: "productService") |
| 296 | + |
| 297 | +// Retrieve types |
| 298 | +if let userServiceType = TypeRegistry.shared.find(for: "userService") { |
| 299 | + let service = userServiceType.init() |
| 300 | + // Use service |
| 301 | +} |
| 302 | +``` |
| 303 | + |
| 304 | +## Choosing the Right Pattern |
| 305 | + |
| 306 | +### When to Use Singleton |
| 307 | +- You need exactly one instance of a class |
| 308 | +- Global access is required |
| 309 | +- Resource management (database connections, caches) |
| 310 | + |
| 311 | +### When to Use Factory |
| 312 | +- Object creation logic is complex |
| 313 | +- You want to decouple object creation from usage |
| 314 | +- You need to create objects based on runtime conditions |
| 315 | + |
| 316 | +### When to Use Builder |
| 317 | +- Object has many optional parameters |
| 318 | +- You want immutable objects |
| 319 | +- Step-by-step construction is clearer than a large initializer |
| 320 | + |
| 321 | +### When to Use Adapter |
| 322 | +- You need to integrate incompatible interfaces |
| 323 | +- Working with legacy code |
| 324 | +- Third-party library integration |
| 325 | + |
| 326 | +### When to Use Facade |
| 327 | +- You want to simplify a complex subsystem |
| 328 | +- Hide implementation details |
| 329 | +- Provide a unified interface |
| 330 | + |
| 331 | +### When to Use Strategy |
| 332 | +- You have multiple ways to accomplish a task |
| 333 | +- Algorithm selection at runtime |
| 334 | +- You want to avoid conditional statements for algorithm selection |
| 335 | + |
| 336 | +### When to Use Observer |
| 337 | +- You need to notify multiple objects of state changes |
| 338 | +- Decoupling senders and receivers |
| 339 | +- Event-driven architectures |
| 340 | + |
| 341 | +## Best Practices |
| 342 | + |
| 343 | +1. **Prefer Protocols**: Use protocols to define interfaces, making patterns more flexible and testable |
| 344 | +2. **Thread Safety**: Consider thread safety for singletons and shared state |
| 345 | +3. **Swift Concurrency**: Use actors for thread-safe singletons in async/await contexts |
| 346 | +4. **Immutability**: Prefer immutable objects where possible |
| 347 | +5. **Testability**: Design patterns should make code more testable, not less |
| 348 | +6. **Documentation**: Document when and why to use each pattern |
| 349 | + |
| 350 | +## References |
| 351 | + |
| 352 | +- [Design Patterns: Elements of Reusable Object-Oriented Software](https://en.wikipedia.org/wiki/Design_Patterns) |
| 353 | +- [Swift Design Patterns](https://softwarepatternslexicon.com/swift/introduction-to-design-patterns-in-swift/) |
| 354 | +- [Apple Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/) |
| 355 | + |
0 commit comments