├── .github
├── FUNDING.yml
└── workflows
│ └── generate-playground.yml
├── .gitignore
├── CONTRIBUTING.md
├── Design-Patterns-CN.playground.zip
├── Design-Patterns-CN.playground
├── Pages
│ ├── Behavioral.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Creational.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Index.xcplaygroundpage
│ │ └── Contents.swift
│ └── Structural.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── timeline.xctimeline
└── contents.xcplayground
├── Design-Patterns.playground.zip
├── Design-Patterns.playground
├── Pages
│ ├── Behavioral.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Creational.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Index.xcplaygroundpage
│ │ └── Contents.swift
│ └── Structural.xcplaygroundpage
│ │ ├── Contents.swift
│ │ └── timeline.xctimeline
└── contents.xcplayground
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README-CN.md
├── README.md
├── generate-playground-cn.sh
├── generate-playground.sh
├── source-cn
├── Index
│ ├── header.md
│ └── welcome.swift
├── behavioral
│ ├── chain_of_responsibility.swift
│ ├── command.swift
│ ├── header.md
│ ├── interpreter.swift
│ ├── iterator.swift
│ ├── mediator.swift
│ ├── memento.swift
│ ├── observer.swift
│ ├── state.swift
│ ├── strategy.swift
│ ├── template_method.swift
│ └── visitor.swift
├── contents.md
├── contentsReadme.md
├── creational
│ ├── abstract_factory.swift
│ ├── builder.swift
│ ├── factory.swift
│ ├── header.md
│ ├── monostate.swift
│ ├── prototype.swift
│ └── singleton.swift
├── endComment
├── endSwiftCode
├── footer.md
├── imports.swift
├── startComment
├── startSwiftCode
└── structural
│ ├── adapter.swift
│ ├── bridge.swift
│ ├── composite.swift
│ ├── decorator.swift
│ ├── facade.swift
│ ├── flyweight.swift
│ ├── header.md
│ ├── protection_proxy.swift
│ └── virtual_proxy.swift
└── source
├── Index
├── header.md
└── welcome.swift
├── behavioral
├── chain_of_responsibility.swift
├── command.swift
├── header.md
├── interpreter.swift
├── iterator.swift
├── mediator.swift
├── memento.swift
├── observer.swift
├── state.swift
├── strategy.swift
├── template_method.swift
└── visitor.swift
├── contents.md
├── contentsReadme.md
├── creational
├── abstract_factory.swift
├── builder.swift
├── factory.swift
├── header.md
├── monostate.swift
├── prototype.swift
└── singleton.swift
├── endComment
├── endSwiftCode
├── footer.md
├── imports.swift
├── startComment
├── startSwiftCode
└── structural
├── adapter.swift
├── bridge.swift
├── composite.swift
├── decorator.swift
├── facade.swift
├── flyweight.swift
├── header.md
├── protection_proxy.swift
└── virtual_proxy.swift
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: ochococo
4 |
--------------------------------------------------------------------------------
/.github/workflows/generate-playground.yml:
--------------------------------------------------------------------------------
1 | name: Generate Playground Files and READMES
2 |
3 | # Controls when the action will run. Triggers the workflow on push or pull request
4 | # events but only for the master branch
5 | on:
6 | push:
7 | branches: [master]
8 |
9 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel
10 | jobs:
11 | # This workflow contains a single job called "build"
12 | generate-playgrounds:
13 | # The type of runner that the job will run on
14 | runs-on: macos-latest
15 |
16 | # Steps represent a sequence of tasks that will be executed as part of the job
17 | steps:
18 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
19 | - uses: actions/checkout@v2
20 |
21 | # Checkout & Generate
22 | - name: Generate playgrounds and readmes
23 | run: |
24 | ./generate-playground.sh
25 | ./generate-playground-cn.sh
26 |
27 | # Commit
28 | - name: Commit files
29 | run: |
30 | git config --local user.email "action@github.com"
31 | git config --local user.name "GitHub Action"
32 | git add Design-Patterns-CN.playground.zip
33 | git add Design-Patterns.playground.zip
34 | git add README.md
35 | git add README-CN.md
36 | git commit -m "Generate Playground"
37 | ## Push changes to master branch
38 | - name: Push changes
39 | uses: ad-m/github-push-action@master
40 | with:
41 | github_token: ${{ secrets.GITHUB_TOKEN }}
42 | branch: "master"
43 | force: false
44 |
45 | # This workflow contains a single job called "build"
46 | generate-chinese-branch:
47 | needs: generate-playgrounds
48 | # The type of runner that the job will run on
49 | runs-on: macos-latest
50 |
51 | # Steps represent a sequence of tasks that will be executed as part of the job
52 | steps:
53 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
54 | - uses: actions/checkout@v2
55 |
56 | # Checkout & Generate
57 | - name: Generate Chinese Readme
58 | run: |
59 | ./generate-playground-cn.sh
60 | mv ./README-CN.md ./README.md
61 |
62 | # Commit
63 | - name: Commit files
64 | run: |
65 | git config --local user.email "action@github.com"
66 | git config --local user.name "GitHub Action"
67 | git add README.md
68 | git commit -m "Generate Chinese version"
69 | ## Push changes to chinese branch
70 | - name: Push changes
71 | uses: ad-m/github-push-action@master
72 | with:
73 | github_token: ${{ secrets.GITHUB_TOKEN }}
74 | branch: "chinese"
75 | force: true
76 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | UserInterfaceState.xcuserstate
3 | playground.xcworkspace
4 | xcuserdata
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | How to contribute?
2 | ==================
3 |
4 | - You are awesome!
5 | - Only editing files inside `source` is recommended, the rest is autogenerated and translated
6 | - Run `generate-playground.sh` locally
7 | - Opene the .playground locally and check if it works
8 | - Please be patient and respectful to fellow contributors
9 |
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/evnaz/Design-Patterns-In-Swift/bd6dfaf9a241d418b3ec70a9faa275ffe279865e/Design-Patterns-CN.playground.zip
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | 行为型模式
4 | ========
5 |
6 | >在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。
7 | >
8 | >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
9 |
10 | ## 目录
11 |
12 | * [行为型模式](Behavioral)
13 | * [创建型模式](Creational)
14 | * [结构型模式](Structural)
15 | */
16 | import Foundation
17 | /*:
18 | 🐝 责任链(Chain Of Responsibility)
19 | ------------------------------
20 |
21 | 责任链模式在面向对象程式设计里是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。
22 |
23 | ### 示例:
24 | */
25 |
26 | protocol Withdrawing {
27 | func withdraw(amount: Int) -> Bool
28 | }
29 |
30 | final class MoneyPile: Withdrawing {
31 |
32 | let value: Int
33 | var quantity: Int
34 | var next: Withdrawing?
35 |
36 | init(value: Int, quantity: Int, next: Withdrawing?) {
37 | self.value = value
38 | self.quantity = quantity
39 | self.next = next
40 | }
41 |
42 | func withdraw(amount: Int) -> Bool {
43 |
44 | var amount = amount
45 |
46 | func canTakeSomeBill(want: Int) -> Bool {
47 | return (want / self.value) > 0
48 | }
49 |
50 | var quantity = self.quantity
51 |
52 | while canTakeSomeBill(want: amount) {
53 |
54 | if quantity == 0 {
55 | break
56 | }
57 |
58 | amount -= self.value
59 | quantity -= 1
60 | }
61 |
62 | guard amount > 0 else {
63 | return true
64 | }
65 |
66 | if let next = self.next {
67 | return next.withdraw(amount: amount)
68 | }
69 |
70 | return false
71 | }
72 | }
73 |
74 | final class ATM: Withdrawing {
75 |
76 | private var hundred: Withdrawing
77 | private var fifty: Withdrawing
78 | private var twenty: Withdrawing
79 | private var ten: Withdrawing
80 |
81 | private var startPile: Withdrawing {
82 | return self.hundred
83 | }
84 |
85 | init(hundred: Withdrawing,
86 | fifty: Withdrawing,
87 | twenty: Withdrawing,
88 | ten: Withdrawing) {
89 |
90 | self.hundred = hundred
91 | self.fifty = fifty
92 | self.twenty = twenty
93 | self.ten = ten
94 | }
95 |
96 | func withdraw(amount: Int) -> Bool {
97 | return startPile.withdraw(amount: amount)
98 | }
99 | }
100 | /*:
101 | ### 用法
102 | */
103 | // 创建一系列的钱堆,并将其链接起来:10<20<50<100
104 | let ten = MoneyPile(value: 10, quantity: 6, next: nil)
105 | let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
106 | let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
107 | let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
108 |
109 | // 创建 ATM 实例
110 | var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
111 | atm.withdraw(amount: 310) // Cannot because ATM has only 300
112 | atm.withdraw(amount: 100) // Can withdraw - 1x100
113 | /*:
114 | 👫 命令(Command)
115 | ------------
116 | 命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:
117 | * 重复多次
118 | * 取消(如果该对象有实现的话)
119 | * 取消后又再重做
120 | ### 示例:
121 | */
122 | protocol DoorCommand {
123 | func execute() -> String
124 | }
125 |
126 | final class OpenCommand: DoorCommand {
127 | let doors:String
128 |
129 | required init(doors: String) {
130 | self.doors = doors
131 | }
132 |
133 | func execute() -> String {
134 | return "Opened \(doors)"
135 | }
136 | }
137 |
138 | final class CloseCommand: DoorCommand {
139 | let doors:String
140 |
141 | required init(doors: String) {
142 | self.doors = doors
143 | }
144 |
145 | func execute() -> String {
146 | return "Closed \(doors)"
147 | }
148 | }
149 |
150 | final class HAL9000DoorsOperations {
151 | let openCommand: DoorCommand
152 | let closeCommand: DoorCommand
153 |
154 | init(doors: String) {
155 | self.openCommand = OpenCommand(doors:doors)
156 | self.closeCommand = CloseCommand(doors:doors)
157 | }
158 |
159 | func close() -> String {
160 | return closeCommand.execute()
161 | }
162 |
163 | func open() -> String {
164 | return openCommand.execute()
165 | }
166 | }
167 | /*:
168 | ### 用法
169 | */
170 | let podBayDoors = "Pod Bay Doors"
171 | let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
172 |
173 | doorModule.open()
174 | doorModule.close()
175 | /*:
176 | 🎶 解释器(Interpreter)
177 | ------------------
178 |
179 | 给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
180 |
181 | ### 示例:
182 | */
183 |
184 | protocol IntegerExpression {
185 | func evaluate(_ context: IntegerContext) -> Int
186 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
187 | func copied() -> IntegerExpression
188 | }
189 |
190 | final class IntegerContext {
191 | private var data: [Character:Int] = [:]
192 |
193 | func lookup(name: Character) -> Int {
194 | return self.data[name]!
195 | }
196 |
197 | func assign(expression: IntegerVariableExpression, value: Int) {
198 | self.data[expression.name] = value
199 | }
200 | }
201 |
202 | final class IntegerVariableExpression: IntegerExpression {
203 | let name: Character
204 |
205 | init(name: Character) {
206 | self.name = name
207 | }
208 |
209 | func evaluate(_ context: IntegerContext) -> Int {
210 | return context.lookup(name: self.name)
211 | }
212 |
213 | func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
214 | if name == self.name {
215 | return integerExpression.copied()
216 | } else {
217 | return IntegerVariableExpression(name: self.name)
218 | }
219 | }
220 |
221 | func copied() -> IntegerExpression {
222 | return IntegerVariableExpression(name: self.name)
223 | }
224 | }
225 |
226 | final class AddExpression: IntegerExpression {
227 | private var operand1: IntegerExpression
228 | private var operand2: IntegerExpression
229 |
230 | init(op1: IntegerExpression, op2: IntegerExpression) {
231 | self.operand1 = op1
232 | self.operand2 = op2
233 | }
234 |
235 | func evaluate(_ context: IntegerContext) -> Int {
236 | return self.operand1.evaluate(context) + self.operand2.evaluate(context)
237 | }
238 |
239 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
240 | return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
241 | op2: operand2.replace(character: character, integerExpression: integerExpression))
242 | }
243 |
244 | func copied() -> IntegerExpression {
245 | return AddExpression(op1: self.operand1, op2: self.operand2)
246 | }
247 | }
248 | /*:
249 | ### 用法
250 | */
251 | var context = IntegerContext()
252 |
253 | var a = IntegerVariableExpression(name: "A")
254 | var b = IntegerVariableExpression(name: "B")
255 | var c = IntegerVariableExpression(name: "C")
256 |
257 | var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
258 |
259 | context.assign(expression: a, value: 2)
260 | context.assign(expression: b, value: 1)
261 | context.assign(expression: c, value: 3)
262 |
263 | var result = expression.evaluate(context)
264 | /*:
265 | 🍫 迭代器(Iterator)
266 | ---------------
267 |
268 | 迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。
269 |
270 | ### 示例:
271 | */
272 | struct Novella {
273 | let name: String
274 | }
275 |
276 | struct Novellas {
277 | let novellas: [Novella]
278 | }
279 |
280 | struct NovellasIterator: IteratorProtocol {
281 |
282 | private var current = 0
283 | private let novellas: [Novella]
284 |
285 | init(novellas: [Novella]) {
286 | self.novellas = novellas
287 | }
288 |
289 | mutating func next() -> Novella? {
290 | defer { current += 1 }
291 | return novellas.count > current ? novellas[current] : nil
292 | }
293 | }
294 |
295 | extension Novellas: Sequence {
296 | func makeIterator() -> NovellasIterator {
297 | return NovellasIterator(novellas: novellas)
298 | }
299 | }
300 | /*:
301 | ### 用法
302 | */
303 | let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
304 |
305 | for novella in greatNovellas {
306 | print("I've read: \(novella)")
307 | }
308 | /*:
309 | 💐 中介者(Mediator)
310 | ---------------
311 |
312 | 用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互。
313 |
314 | ### 示例:
315 | */
316 | protocol Receiver {
317 | associatedtype MessageType
318 | func receive(message: MessageType)
319 | }
320 |
321 | protocol Sender {
322 | associatedtype MessageType
323 | associatedtype ReceiverType: Receiver
324 |
325 | var recipients: [ReceiverType] { get }
326 |
327 | func send(message: MessageType)
328 | }
329 |
330 | struct Programmer: Receiver {
331 | let name: String
332 |
333 | init(name: String) {
334 | self.name = name
335 | }
336 |
337 | func receive(message: String) {
338 | print("\(name) received: \(message)")
339 | }
340 | }
341 |
342 | final class MessageMediator: Sender {
343 | internal var recipients: [Programmer] = []
344 |
345 | func add(recipient: Programmer) {
346 | recipients.append(recipient)
347 | }
348 |
349 | func send(message: String) {
350 | for recipient in recipients {
351 | recipient.receive(message: message)
352 | }
353 | }
354 | }
355 |
356 | /*:
357 | ### 用法
358 | */
359 | func spamMonster(message: String, worker: MessageMediator) {
360 | worker.send(message: message)
361 | }
362 |
363 | let messagesMediator = MessageMediator()
364 |
365 | let user0 = Programmer(name: "Linus Torvalds")
366 | let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
367 | messagesMediator.add(recipient: user0)
368 | messagesMediator.add(recipient: user1)
369 |
370 | spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
371 |
372 | /*:
373 | 💾 备忘录(Memento)
374 | --------------
375 |
376 | 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
377 |
378 | ### 示例:
379 | */
380 | typealias Memento = [String: String]
381 | /*:
382 | 发起人(Originator)
383 | */
384 | protocol MementoConvertible {
385 | var memento: Memento { get }
386 | init?(memento: Memento)
387 | }
388 |
389 | struct GameState: MementoConvertible {
390 |
391 | private enum Keys {
392 | static let chapter = "com.valve.halflife.chapter"
393 | static let weapon = "com.valve.halflife.weapon"
394 | }
395 |
396 | var chapter: String
397 | var weapon: String
398 |
399 | init(chapter: String, weapon: String) {
400 | self.chapter = chapter
401 | self.weapon = weapon
402 | }
403 |
404 | init?(memento: Memento) {
405 | guard let mementoChapter = memento[Keys.chapter],
406 | let mementoWeapon = memento[Keys.weapon] else {
407 | return nil
408 | }
409 |
410 | chapter = mementoChapter
411 | weapon = mementoWeapon
412 | }
413 |
414 | var memento: Memento {
415 | return [ Keys.chapter: chapter, Keys.weapon: weapon ]
416 | }
417 | }
418 | /*:
419 | 管理者(Caretaker)
420 | */
421 | enum CheckPoint {
422 |
423 | private static let defaults = UserDefaults.standard
424 |
425 | static func save(_ state: MementoConvertible, saveName: String) {
426 | defaults.set(state.memento, forKey: saveName)
427 | defaults.synchronize()
428 | }
429 |
430 | static func restore(saveName: String) -> Any? {
431 | return defaults.object(forKey: saveName)
432 | }
433 | }
434 | /*:
435 | ### 用法
436 | */
437 | var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
438 |
439 | gameState.chapter = "Anomalous Materials"
440 | gameState.weapon = "Glock 17"
441 | CheckPoint.save(gameState, saveName: "gameState1")
442 |
443 | gameState.chapter = "Unforeseen Consequences"
444 | gameState.weapon = "MP5"
445 | CheckPoint.save(gameState, saveName: "gameState2")
446 |
447 | gameState.chapter = "Office Complex"
448 | gameState.weapon = "Crossbow"
449 | CheckPoint.save(gameState, saveName: "gameState3")
450 |
451 | if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
452 | let finalState = GameState(memento: memento)
453 | dump(finalState)
454 | }
455 | /*:
456 | 👓 观察者(Observer)
457 | ---------------
458 |
459 | 一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知
460 |
461 | ### 示例:
462 | */
463 | protocol PropertyObserver : class {
464 | func willChange(propertyName: String, newPropertyValue: Any?)
465 | func didChange(propertyName: String, oldPropertyValue: Any?)
466 | }
467 |
468 | final class TestChambers {
469 |
470 | weak var observer:PropertyObserver?
471 |
472 | private let testChamberNumberName = "testChamberNumber"
473 |
474 | var testChamberNumber: Int = 0 {
475 | willSet(newValue) {
476 | observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
477 | }
478 | didSet {
479 | observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
480 | }
481 | }
482 | }
483 |
484 | final class Observer : PropertyObserver {
485 | func willChange(propertyName: String, newPropertyValue: Any?) {
486 | if newPropertyValue as? Int == 1 {
487 | print("Okay. Look. We both said a lot of things that you're going to regret.")
488 | }
489 | }
490 |
491 | func didChange(propertyName: String, oldPropertyValue: Any?) {
492 | if oldPropertyValue as? Int == 0 {
493 | print("Sorry about the mess. I've really let the place go since you killed me.")
494 | }
495 | }
496 | }
497 | /*:
498 | ### 用法
499 | */
500 | var observerInstance = Observer()
501 | var testChambers = TestChambers()
502 | testChambers.observer = observerInstance
503 | testChambers.testChamberNumber += 1
504 | /*:
505 | 🐉 状态(State)
506 | ---------
507 |
508 | 在状态模式中,对象的行为是基于它的内部状态而改变的。
509 | 这个模式允许某个类对象在运行时发生改变。
510 |
511 | ### 示例:
512 | */
513 | final class Context {
514 | private var state: State = UnauthorizedState()
515 |
516 | var isAuthorized: Bool {
517 | get { return state.isAuthorized(context: self) }
518 | }
519 |
520 | var userId: String? {
521 | get { return state.userId(context: self) }
522 | }
523 |
524 | func changeStateToAuthorized(userId: String) {
525 | state = AuthorizedState(userId: userId)
526 | }
527 |
528 | func changeStateToUnauthorized() {
529 | state = UnauthorizedState()
530 | }
531 | }
532 |
533 | protocol State {
534 | func isAuthorized(context: Context) -> Bool
535 | func userId(context: Context) -> String?
536 | }
537 |
538 | class UnauthorizedState: State {
539 | func isAuthorized(context: Context) -> Bool { return false }
540 |
541 | func userId(context: Context) -> String? { return nil }
542 | }
543 |
544 | class AuthorizedState: State {
545 | let userId: String
546 |
547 | init(userId: String) { self.userId = userId }
548 |
549 | func isAuthorized(context: Context) -> Bool { return true }
550 |
551 | func userId(context: Context) -> String? { return userId }
552 | }
553 | /*:
554 | ### 用法
555 | */
556 | let userContext = Context()
557 | (userContext.isAuthorized, userContext.userId)
558 | userContext.changeStateToAuthorized(userId: "admin")
559 | (userContext.isAuthorized, userContext.userId) // now logged in as "admin"
560 | userContext.changeStateToUnauthorized()
561 | (userContext.isAuthorized, userContext.userId)
562 | /*:
563 | 💡 策略(Strategy)
564 | --------------
565 |
566 | 对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:
567 | * 定义了一族算法(业务规则);
568 | * 封装了每个算法;
569 | * 这族的算法可互换代替(interchangeable)。
570 |
571 | ### 示例:
572 | */
573 |
574 | struct TestSubject {
575 | let pupilDiameter: Double
576 | let blushResponse: Double
577 | let isOrganic: Bool
578 | }
579 |
580 | protocol RealnessTesting: AnyObject {
581 | func testRealness(_ testSubject: TestSubject) -> Bool
582 | }
583 |
584 | final class VoightKampffTest: RealnessTesting {
585 | func testRealness(_ testSubject: TestSubject) -> Bool {
586 | return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
587 | }
588 | }
589 |
590 | final class GeneticTest: RealnessTesting {
591 | func testRealness(_ testSubject: TestSubject) -> Bool {
592 | return testSubject.isOrganic
593 | }
594 | }
595 |
596 | final class BladeRunner {
597 | private let strategy: RealnessTesting
598 |
599 | init(test: RealnessTesting) {
600 | self.strategy = test
601 | }
602 |
603 | func testIfAndroid(_ testSubject: TestSubject) -> Bool {
604 | return !strategy.testRealness(testSubject)
605 | }
606 | }
607 |
608 | /*:
609 | ### 用法
610 | */
611 |
612 | let rachel = TestSubject(pupilDiameter: 30.2,
613 | blushResponse: 0.3,
614 | isOrganic: false)
615 |
616 | // Deckard is using a traditional test
617 | let deckard = BladeRunner(test: VoightKampffTest())
618 | let isRachelAndroid = deckard.testIfAndroid(rachel)
619 |
620 | // Gaff is using a very precise method
621 | let gaff = BladeRunner(test: GeneticTest())
622 | let isDeckardAndroid = gaff.testIfAndroid(rachel)
623 | /*:
624 | 📝 模板方法模式
625 | -----------
626 |
627 | 模板方法模式是一种行为设计模式, 它通过父类/协议中定义了一个算法的框架, 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。
628 |
629 | ### 示例:
630 | */
631 | protocol Garden {
632 | func prepareSoil()
633 | func plantSeeds()
634 | func waterPlants()
635 | func prepareGarden()
636 | }
637 |
638 | extension Garden {
639 |
640 | func prepareGarden() {
641 | prepareSoil()
642 | plantSeeds()
643 | waterPlants()
644 | }
645 | }
646 |
647 | final class RoseGarden: Garden {
648 |
649 | func prepare() {
650 | prepareGarden()
651 | }
652 |
653 | func prepareSoil() {
654 | print ("prepare soil for rose garden")
655 | }
656 |
657 | func plantSeeds() {
658 | print ("plant seeds for rose garden")
659 | }
660 |
661 | func waterPlants() {
662 | print ("water the rose garden")
663 | }
664 | }
665 |
666 | /*:
667 | ### 用法
668 | */
669 |
670 | let roseGarden = RoseGarden()
671 | roseGarden.prepare()
672 | /*:
673 | 🏃 访问者(Visitor)
674 | --------------
675 |
676 | 封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
677 |
678 | ### 示例:
679 | */
680 | protocol PlanetVisitor {
681 | func visit(planet: PlanetAlderaan)
682 | func visit(planet: PlanetCoruscant)
683 | func visit(planet: PlanetTatooine)
684 | func visit(planet: MoonJedha)
685 | }
686 |
687 | protocol Planet {
688 | func accept(visitor: PlanetVisitor)
689 | }
690 |
691 | final class MoonJedha: Planet {
692 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
693 | }
694 |
695 | final class PlanetAlderaan: Planet {
696 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
697 | }
698 |
699 | final class PlanetCoruscant: Planet {
700 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
701 | }
702 |
703 | final class PlanetTatooine: Planet {
704 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
705 | }
706 |
707 | final class NameVisitor: PlanetVisitor {
708 | var name = ""
709 |
710 | func visit(planet: PlanetAlderaan) { name = "Alderaan" }
711 | func visit(planet: PlanetCoruscant) { name = "Coruscant" }
712 | func visit(planet: PlanetTatooine) { name = "Tatooine" }
713 | func visit(planet: MoonJedha) { name = "Jedha" }
714 | }
715 |
716 | /*:
717 | ### 用法
718 | */
719 | let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
720 |
721 | let names = planets.map { (planet: Planet) -> String in
722 | let visitor = NameVisitor()
723 | planet.accept(visitor: visitor)
724 |
725 | return visitor.name
726 | }
727 |
728 | names
729 |
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground/Pages/Creational.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | 创建型模式
4 | ========
5 |
6 | > 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。
7 | >
8 | >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
9 |
10 | ## 目录
11 |
12 | * [行为型模式](Behavioral)
13 | * [创建型模式](Creational)
14 | * [结构型模式](Structural)
15 | */
16 | import Foundation
17 | /*:
18 | 🌰 抽象工厂(Abstract Factory)
19 | -------------
20 |
21 | 抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。
22 |
23 | ### 示例:
24 |
25 | 协议
26 | */
27 |
28 | protocol BurgerDescribing {
29 | var ingredients: [String] { get }
30 | }
31 |
32 | struct CheeseBurger: BurgerDescribing {
33 | let ingredients: [String]
34 | }
35 |
36 | protocol BurgerMaking {
37 | func make() -> BurgerDescribing
38 | }
39 |
40 | // 工厂方法实现
41 |
42 | final class BigKahunaBurger: BurgerMaking {
43 | func make() -> BurgerDescribing {
44 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
45 | }
46 | }
47 |
48 | final class JackInTheBox: BurgerMaking {
49 | func make() -> BurgerDescribing {
50 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
51 | }
52 | }
53 |
54 | /*:
55 | 抽象工厂
56 | */
57 |
58 | enum BurgerFactoryType: BurgerMaking {
59 |
60 | case bigKahuna
61 | case jackInTheBox
62 |
63 | func make() -> BurgerDescribing {
64 | switch self {
65 | case .bigKahuna:
66 | return BigKahunaBurger().make()
67 | case .jackInTheBox:
68 | return JackInTheBox().make()
69 | }
70 | }
71 | }
72 | /*:
73 | ### 用法
74 | */
75 | let bigKahuna = BurgerFactoryType.bigKahuna.make()
76 | let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
77 | /*:
78 | 👷 生成器(Builder)
79 | --------------
80 |
81 | 一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。
82 |
83 | ### 示例:
84 | */
85 | final class DeathStarBuilder {
86 |
87 | var x: Double?
88 | var y: Double?
89 | var z: Double?
90 |
91 | typealias BuilderClosure = (DeathStarBuilder) -> ()
92 |
93 | init(buildClosure: BuilderClosure) {
94 | buildClosure(self)
95 | }
96 | }
97 |
98 | struct DeathStar : CustomStringConvertible {
99 |
100 | let x: Double
101 | let y: Double
102 | let z: Double
103 |
104 | init?(builder: DeathStarBuilder) {
105 |
106 | if let x = builder.x, let y = builder.y, let z = builder.z {
107 | self.x = x
108 | self.y = y
109 | self.z = z
110 | } else {
111 | return nil
112 | }
113 | }
114 |
115 | var description:String {
116 | return "Death Star at (x:\(x) y:\(y) z:\(z))"
117 | }
118 | }
119 | /*:
120 | ### 用法
121 | */
122 | let empire = DeathStarBuilder { builder in
123 | builder.x = 0.1
124 | builder.y = 0.2
125 | builder.z = 0.3
126 | }
127 |
128 | let deathStar = DeathStar(builder:empire)
129 | /*:
130 | 🏭 工厂方法(Factory Method)
131 | -----------------------
132 |
133 | 定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
134 |
135 | ### 示例:
136 | */
137 | protocol CurrencyDescribing {
138 | var symbol: String { get }
139 | var code: String { get }
140 | }
141 |
142 | final class Euro: CurrencyDescribing {
143 | var symbol: String {
144 | return "€"
145 | }
146 |
147 | var code: String {
148 | return "EUR"
149 | }
150 | }
151 |
152 | final class UnitedStatesDolar: CurrencyDescribing {
153 | var symbol: String {
154 | return "$"
155 | }
156 |
157 | var code: String {
158 | return "USD"
159 | }
160 | }
161 |
162 | enum Country {
163 | case unitedStates
164 | case spain
165 | case uk
166 | case greece
167 | }
168 |
169 | enum CurrencyFactory {
170 | static func currency(for country: Country) -> CurrencyDescribing? {
171 |
172 | switch country {
173 | case .spain, .greece:
174 | return Euro()
175 | case .unitedStates:
176 | return UnitedStatesDolar()
177 | default:
178 | return nil
179 | }
180 |
181 | }
182 | }
183 | /*:
184 | ### 用法
185 | */
186 | let noCurrencyCode = "No Currency Code Available"
187 |
188 | CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
189 | CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
190 | CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
191 | CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
192 | /*:
193 | 🔂 单态(Monostate)
194 | ------------
195 |
196 | 单态模式是实现单一共享的另一种方法。不同于单例模式,它通过完全不同的机制,在不限制构造方法的情况下实现单一共享特性。
197 | 因此,在这种情况下,单态会将状态保存为静态,而不是将整个实例保存为单例。
198 | [单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
199 |
200 | ### 示例:
201 | */
202 | class Settings {
203 |
204 | enum Theme {
205 | case `default`
206 | case old
207 | case new
208 | }
209 |
210 | private static var theme: Theme?
211 |
212 | var currentTheme: Theme {
213 | get { Settings.theme ?? .default }
214 | set(newTheme) { Settings.theme = newTheme }
215 | }
216 | }
217 | /*:
218 | ### 用法:
219 | */
220 | import SwiftUI
221 |
222 | // 改变主题
223 | let settings = Settings() // 开始使用主题 .old
224 | settings.currentTheme = .new // 改变主题为 .new
225 |
226 | // 界面一
227 | let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
228 |
229 | // 界面二
230 | let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
231 | /*:
232 | 🃏 原型(Prototype)
233 | --------------
234 |
235 | 通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。
236 |
237 | ### 示例:
238 | */
239 | class MoonWorker {
240 |
241 | let name: String
242 | var health: Int = 100
243 |
244 | init(name: String) {
245 | self.name = name
246 | }
247 |
248 | func clone() -> MoonWorker {
249 | return MoonWorker(name: name)
250 | }
251 | }
252 | /*:
253 | ### 用法
254 | */
255 | let prototype = MoonWorker(name: "Sam Bell")
256 |
257 | var bell1 = prototype.clone()
258 | bell1.health = 12
259 |
260 | var bell2 = prototype.clone()
261 | bell2.health = 23
262 |
263 | var bell3 = prototype.clone()
264 | bell3.health = 0
265 | /*:
266 | 💍 单例(Singleton)
267 | --------------
268 |
269 | 单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为
270 |
271 | ### 示例:
272 | */
273 | final class ElonMusk {
274 |
275 | static let shared = ElonMusk()
276 |
277 | private init() {
278 | // Private initialization to ensure just one instance is created.
279 | }
280 | }
281 | /*:
282 | ### 用法
283 | */
284 | let elon = ElonMusk.shared // There is only one Elon Musk folks.
285 |
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground/Pages/Index.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | 设计模式(Swift 5.0 实现)
4 | ======================
5 |
6 | ([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).
7 |
8 | 👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。
9 |
10 | 🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。
11 |
12 | ## 目录
13 |
14 | * [行为型模式](Behavioral)
15 | * [创建型模式](Creational)
16 | * [结构型模式](Structural)
17 | */
18 | import Foundation
19 |
20 | print("您好!")
21 |
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | 结构型模式(Structural)
4 | ====================
5 |
6 | > 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。
7 | >
8 | >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)
9 |
10 | ## 目录
11 |
12 | * [行为型模式](Behavioral)
13 | * [创建型模式](Creational)
14 | * [结构型模式](Structural)
15 | */
16 | import Foundation
17 | /*:
18 | 🔌 适配器(Adapter)
19 | --------------
20 |
21 | 适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
22 |
23 | ### 示例:
24 | */
25 | protocol NewDeathStarSuperLaserAiming {
26 | var angleV: Double { get }
27 | var angleH: Double { get }
28 | }
29 | /*:
30 | **被适配者**
31 | */
32 | struct OldDeathStarSuperlaserTarget {
33 | let angleHorizontal: Float
34 | let angleVertical: Float
35 |
36 | init(angleHorizontal: Float, angleVertical: Float) {
37 | self.angleHorizontal = angleHorizontal
38 | self.angleVertical = angleVertical
39 | }
40 | }
41 | /*:
42 | **适配器**
43 | */
44 | struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
45 |
46 | private let target: OldDeathStarSuperlaserTarget
47 |
48 | var angleV: Double {
49 | return Double(target.angleVertical)
50 | }
51 |
52 | var angleH: Double {
53 | return Double(target.angleHorizontal)
54 | }
55 |
56 | init(_ target: OldDeathStarSuperlaserTarget) {
57 | self.target = target
58 | }
59 | }
60 | /*:
61 | ### 用法
62 | */
63 | let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
64 | let newFormat = NewDeathStarSuperlaserTarget(target)
65 |
66 | newFormat.angleH
67 | newFormat.angleV
68 | /*:
69 | 🌉 桥接(Bridge)
70 | -----------
71 |
72 | 桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。
73 |
74 | ### 示例:
75 | */
76 | protocol Switch {
77 | var appliance: Appliance { get set }
78 | func turnOn()
79 | }
80 |
81 | protocol Appliance {
82 | func run()
83 | }
84 |
85 | final class RemoteControl: Switch {
86 | var appliance: Appliance
87 |
88 | func turnOn() {
89 | self.appliance.run()
90 | }
91 |
92 | init(appliance: Appliance) {
93 | self.appliance = appliance
94 | }
95 | }
96 |
97 | final class TV: Appliance {
98 | func run() {
99 | print("tv turned on");
100 | }
101 | }
102 |
103 | final class VacuumCleaner: Appliance {
104 | func run() {
105 | print("vacuum cleaner turned on")
106 | }
107 | }
108 | /*:
109 | ### 用法
110 | */
111 | let tvRemoteControl = RemoteControl(appliance: TV())
112 | tvRemoteControl.turnOn()
113 |
114 | let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
115 | fancyVacuumCleanerRemoteControl.turnOn()
116 | /*:
117 | 🌿 组合(Composite)
118 | --------------
119 |
120 | 将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
121 |
122 | ### 示例:
123 |
124 | 组件(Component)
125 | */
126 | protocol Shape {
127 | func draw(fillColor: String)
128 | }
129 | /*:
130 | 叶子节点(Leafs)
131 | */
132 | final class Square: Shape {
133 | func draw(fillColor: String) {
134 | print("Drawing a Square with color \(fillColor)")
135 | }
136 | }
137 |
138 | final class Circle: Shape {
139 | func draw(fillColor: String) {
140 | print("Drawing a circle with color \(fillColor)")
141 | }
142 | }
143 |
144 | /*:
145 | 组合
146 | */
147 | final class Whiteboard: Shape {
148 |
149 | private lazy var shapes = [Shape]()
150 |
151 | init(_ shapes: Shape...) {
152 | self.shapes = shapes
153 | }
154 |
155 | func draw(fillColor: String) {
156 | for shape in self.shapes {
157 | shape.draw(fillColor: fillColor)
158 | }
159 | }
160 | }
161 | /*:
162 | ### 用法
163 | */
164 | var whiteboard = Whiteboard(Circle(), Square())
165 | whiteboard.draw(fillColor: "Red")
166 | /*:
167 | 🍧 修饰(Decorator)
168 | --------------
169 |
170 | 修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。
171 | 就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。
172 |
173 | ### 示例:
174 | */
175 | protocol CostHaving {
176 | var cost: Double { get }
177 | }
178 |
179 | protocol IngredientsHaving {
180 | var ingredients: [String] { get }
181 | }
182 |
183 | typealias BeverageDataHaving = CostHaving & IngredientsHaving
184 |
185 | struct SimpleCoffee: BeverageDataHaving {
186 | let cost: Double = 1.0
187 | let ingredients = ["Water", "Coffee"]
188 | }
189 |
190 | protocol BeverageHaving: BeverageDataHaving {
191 | var beverage: BeverageDataHaving { get }
192 | }
193 |
194 | struct Milk: BeverageHaving {
195 |
196 | let beverage: BeverageDataHaving
197 |
198 | var cost: Double {
199 | return beverage.cost + 0.5
200 | }
201 |
202 | var ingredients: [String] {
203 | return beverage.ingredients + ["Milk"]
204 | }
205 | }
206 |
207 | struct WhipCoffee: BeverageHaving {
208 |
209 | let beverage: BeverageDataHaving
210 |
211 | var cost: Double {
212 | return beverage.cost + 0.5
213 | }
214 |
215 | var ingredients: [String] {
216 | return beverage.ingredients + ["Whip"]
217 | }
218 | }
219 | /*:
220 | ### 用法
221 | */
222 | var someCoffee: BeverageDataHaving = SimpleCoffee()
223 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
224 | someCoffee = Milk(beverage: someCoffee)
225 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
226 | someCoffee = WhipCoffee(beverage: someCoffee)
227 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
228 | /*:
229 | 🎁 外观(Facade)
230 | -----------
231 |
232 | 外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。
233 |
234 | ### 示例:
235 | */
236 | final class Defaults {
237 |
238 | private let defaults: UserDefaults
239 |
240 | init(defaults: UserDefaults = .standard) {
241 | self.defaults = defaults
242 | }
243 |
244 | subscript(key: String) -> String? {
245 | get {
246 | return defaults.string(forKey: key)
247 | }
248 |
249 | set {
250 | defaults.set(newValue, forKey: key)
251 | }
252 | }
253 | }
254 | /*:
255 | ### 用法
256 | */
257 | let storage = Defaults()
258 |
259 | // Store
260 | storage["Bishop"] = "Disconnect me. I’d rather be nothing"
261 |
262 | // Read
263 | storage["Bishop"]
264 | /*:
265 | 🍃 享元(Flyweight)
266 | --------------
267 |
268 | 使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。
269 |
270 | ### 示例:
271 | */
272 | // 特指咖啡生成的对象会是享元
273 | struct SpecialityCoffee {
274 | let origin: String
275 | }
276 |
277 | protocol CoffeeSearching {
278 | func search(origin: String) -> SpecialityCoffee?
279 | }
280 |
281 | // 菜单充当特制咖啡享元对象的工厂和缓存
282 | final class Menu: CoffeeSearching {
283 |
284 | private var coffeeAvailable: [String: SpecialityCoffee] = [:]
285 |
286 | func search(origin: String) -> SpecialityCoffee? {
287 | if coffeeAvailable.index(forKey: origin) == nil {
288 | coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
289 | }
290 |
291 | return coffeeAvailable[origin]
292 | }
293 | }
294 |
295 | final class CoffeeShop {
296 | private var orders: [Int: SpecialityCoffee] = [:]
297 | private let menu: CoffeeSearching
298 |
299 | init(menu: CoffeeSearching) {
300 | self.menu = menu
301 | }
302 |
303 | func takeOrder(origin: String, table: Int) {
304 | orders[table] = menu.search(origin: origin)
305 | }
306 |
307 | func serve() {
308 | for (table, origin) in orders {
309 | print("Serving \(origin) to table \(table)")
310 | }
311 | }
312 | }
313 | /*:
314 | ### 用法
315 | */
316 | let coffeeShop = CoffeeShop(menu: Menu())
317 |
318 | coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
319 | coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
320 |
321 | coffeeShop.serve()
322 | /*:
323 | ☔ 保护代理模式(Protection Proxy)
324 | ------------------
325 |
326 | 在代理模式中,创建一个类代表另一个底层类的功能。
327 | 保护代理用于限制访问。
328 |
329 | ### 示例:
330 | */
331 | protocol DoorOpening {
332 | func open(doors: String) -> String
333 | }
334 |
335 | final class HAL9000: DoorOpening {
336 | func open(doors: String) -> String {
337 | return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
338 | }
339 | }
340 |
341 | final class CurrentComputer: DoorOpening {
342 | private var computer: HAL9000!
343 |
344 | func authenticate(password: String) -> Bool {
345 |
346 | guard password == "pass" else {
347 | return false
348 | }
349 |
350 | computer = HAL9000()
351 |
352 | return true
353 | }
354 |
355 | func open(doors: String) -> String {
356 |
357 | guard computer != nil else {
358 | return "Access Denied. I'm afraid I can't do that."
359 | }
360 |
361 | return computer.open(doors: doors)
362 | }
363 | }
364 | /*:
365 | ### 用法
366 | */
367 | let computer = CurrentComputer()
368 | let podBay = "Pod Bay Doors"
369 |
370 | computer.open(doors: podBay)
371 |
372 | computer.authenticate(password: "pass")
373 | computer.open(doors: podBay)
374 | /*:
375 | 🍬 虚拟代理(Virtual Proxy)
376 | ----------------
377 |
378 | 在代理模式中,创建一个类代表另一个底层类的功能。
379 | 虚拟代理用于对象的需时加载。
380 |
381 | ### 示例:
382 | */
383 | protocol HEVSuitMedicalAid {
384 | func administerMorphine() -> String
385 | }
386 |
387 | final class HEVSuit: HEVSuitMedicalAid {
388 | func administerMorphine() -> String {
389 | return "Morphine administered."
390 | }
391 | }
392 |
393 | final class HEVSuitHumanInterface: HEVSuitMedicalAid {
394 |
395 | lazy private var physicalSuit: HEVSuit = HEVSuit()
396 |
397 | func administerMorphine() -> String {
398 | return physicalSuit.administerMorphine()
399 | }
400 | }
401 | /*:
402 | ### 用法
403 | */
404 | let humanInterface = HEVSuitHumanInterface()
405 | humanInterface.administerMorphine()
406 |
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Design-Patterns-CN.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Design-Patterns.playground.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/evnaz/Design-Patterns-In-Swift/bd6dfaf9a241d418b3ec70a9faa275ffe279865e/Design-Patterns.playground.zip
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | Behavioral
4 | ==========
5 |
6 | >In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
7 | >
8 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
9 |
10 | ## Table of Contents
11 |
12 | * [Behavioral](Behavioral)
13 | * [Creational](Creational)
14 | * [Structural](Structural)
15 |
16 | */
17 | import Foundation
18 | /*:
19 | 🐝 Chain Of Responsibility
20 | --------------------------
21 |
22 | The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
23 |
24 | ### Example:
25 | */
26 |
27 | protocol Withdrawing {
28 | func withdraw(amount: Int) -> Bool
29 | }
30 |
31 | final class MoneyPile: Withdrawing {
32 |
33 | let value: Int
34 | var quantity: Int
35 | var next: Withdrawing?
36 |
37 | init(value: Int, quantity: Int, next: Withdrawing?) {
38 | self.value = value
39 | self.quantity = quantity
40 | self.next = next
41 | }
42 |
43 | func withdraw(amount: Int) -> Bool {
44 |
45 | var amount = amount
46 |
47 | func canTakeSomeBill(want: Int) -> Bool {
48 | return (want / self.value) > 0
49 | }
50 |
51 | var quantity = self.quantity
52 |
53 | while canTakeSomeBill(want: amount) {
54 |
55 | if quantity == 0 {
56 | break
57 | }
58 |
59 | amount -= self.value
60 | quantity -= 1
61 | }
62 |
63 | guard amount > 0 else {
64 | return true
65 | }
66 |
67 | if let next = self.next {
68 | return next.withdraw(amount: amount)
69 | }
70 |
71 | return false
72 | }
73 | }
74 |
75 | final class ATM: Withdrawing {
76 |
77 | private var hundred: Withdrawing
78 | private var fifty: Withdrawing
79 | private var twenty: Withdrawing
80 | private var ten: Withdrawing
81 |
82 | private var startPile: Withdrawing {
83 | return self.hundred
84 | }
85 |
86 | init(hundred: Withdrawing,
87 | fifty: Withdrawing,
88 | twenty: Withdrawing,
89 | ten: Withdrawing) {
90 |
91 | self.hundred = hundred
92 | self.fifty = fifty
93 | self.twenty = twenty
94 | self.ten = ten
95 | }
96 |
97 | func withdraw(amount: Int) -> Bool {
98 | return startPile.withdraw(amount: amount)
99 | }
100 | }
101 | /*:
102 | ### Usage
103 | */
104 | // Create piles of money and link them together 10 < 20 < 50 < 100.**
105 | let ten = MoneyPile(value: 10, quantity: 6, next: nil)
106 | let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
107 | let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
108 | let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
109 |
110 | // Build ATM.
111 | var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
112 | atm.withdraw(amount: 310) // Cannot because ATM has only 300
113 | atm.withdraw(amount: 100) // Can withdraw - 1x100
114 | /*:
115 | 👫 Command
116 | ----------
117 |
118 | The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
119 |
120 | ### Example:
121 | */
122 | protocol DoorCommand {
123 | func execute() -> String
124 | }
125 |
126 | final class OpenCommand: DoorCommand {
127 | let doors:String
128 |
129 | required init(doors: String) {
130 | self.doors = doors
131 | }
132 |
133 | func execute() -> String {
134 | return "Opened \(doors)"
135 | }
136 | }
137 |
138 | final class CloseCommand: DoorCommand {
139 | let doors:String
140 |
141 | required init(doors: String) {
142 | self.doors = doors
143 | }
144 |
145 | func execute() -> String {
146 | return "Closed \(doors)"
147 | }
148 | }
149 |
150 | final class HAL9000DoorsOperations {
151 | let openCommand: DoorCommand
152 | let closeCommand: DoorCommand
153 |
154 | init(doors: String) {
155 | self.openCommand = OpenCommand(doors:doors)
156 | self.closeCommand = CloseCommand(doors:doors)
157 | }
158 |
159 | func close() -> String {
160 | return closeCommand.execute()
161 | }
162 |
163 | func open() -> String {
164 | return openCommand.execute()
165 | }
166 | }
167 | /*:
168 | ### Usage:
169 | */
170 | let podBayDoors = "Pod Bay Doors"
171 | let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
172 |
173 | doorModule.open()
174 | doorModule.close()
175 | /*:
176 | 🎶 Interpreter
177 | --------------
178 |
179 | The interpreter pattern is used to evaluate sentences in a language.
180 |
181 | ### Example
182 | */
183 |
184 | protocol IntegerExpression {
185 | func evaluate(_ context: IntegerContext) -> Int
186 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
187 | func copied() -> IntegerExpression
188 | }
189 |
190 | final class IntegerContext {
191 | private var data: [Character:Int] = [:]
192 |
193 | func lookup(name: Character) -> Int {
194 | return self.data[name]!
195 | }
196 |
197 | func assign(expression: IntegerVariableExpression, value: Int) {
198 | self.data[expression.name] = value
199 | }
200 | }
201 |
202 | final class IntegerVariableExpression: IntegerExpression {
203 | let name: Character
204 |
205 | init(name: Character) {
206 | self.name = name
207 | }
208 |
209 | func evaluate(_ context: IntegerContext) -> Int {
210 | return context.lookup(name: self.name)
211 | }
212 |
213 | func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
214 | if name == self.name {
215 | return integerExpression.copied()
216 | } else {
217 | return IntegerVariableExpression(name: self.name)
218 | }
219 | }
220 |
221 | func copied() -> IntegerExpression {
222 | return IntegerVariableExpression(name: self.name)
223 | }
224 | }
225 |
226 | final class AddExpression: IntegerExpression {
227 | private var operand1: IntegerExpression
228 | private var operand2: IntegerExpression
229 |
230 | init(op1: IntegerExpression, op2: IntegerExpression) {
231 | self.operand1 = op1
232 | self.operand2 = op2
233 | }
234 |
235 | func evaluate(_ context: IntegerContext) -> Int {
236 | return self.operand1.evaluate(context) + self.operand2.evaluate(context)
237 | }
238 |
239 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
240 | return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
241 | op2: operand2.replace(character: character, integerExpression: integerExpression))
242 | }
243 |
244 | func copied() -> IntegerExpression {
245 | return AddExpression(op1: self.operand1, op2: self.operand2)
246 | }
247 | }
248 | /*:
249 | ### Usage
250 | */
251 | var context = IntegerContext()
252 |
253 | var a = IntegerVariableExpression(name: "A")
254 | var b = IntegerVariableExpression(name: "B")
255 | var c = IntegerVariableExpression(name: "C")
256 |
257 | var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
258 |
259 | context.assign(expression: a, value: 2)
260 | context.assign(expression: b, value: 1)
261 | context.assign(expression: c, value: 3)
262 |
263 | var result = expression.evaluate(context)
264 | /*:
265 | 🍫 Iterator
266 | -----------
267 |
268 | The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
269 |
270 | ### Example:
271 | */
272 | struct Novella {
273 | let name: String
274 | }
275 |
276 | struct Novellas {
277 | let novellas: [Novella]
278 | }
279 |
280 | struct NovellasIterator: IteratorProtocol {
281 |
282 | private var current = 0
283 | private let novellas: [Novella]
284 |
285 | init(novellas: [Novella]) {
286 | self.novellas = novellas
287 | }
288 |
289 | mutating func next() -> Novella? {
290 | defer { current += 1 }
291 | return novellas.count > current ? novellas[current] : nil
292 | }
293 | }
294 |
295 | extension Novellas: Sequence {
296 | func makeIterator() -> NovellasIterator {
297 | return NovellasIterator(novellas: novellas)
298 | }
299 | }
300 | /*:
301 | ### Usage
302 | */
303 | let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
304 |
305 | for novella in greatNovellas {
306 | print("I've read: \(novella)")
307 | }
308 | /*:
309 | 💐 Mediator
310 | -----------
311 |
312 | The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
313 |
314 | ### Example
315 | */
316 | protocol Receiver {
317 | associatedtype MessageType
318 | func receive(message: MessageType)
319 | }
320 |
321 | protocol Sender {
322 | associatedtype MessageType
323 | associatedtype ReceiverType: Receiver
324 |
325 | var recipients: [ReceiverType] { get }
326 |
327 | func send(message: MessageType)
328 | }
329 |
330 | struct Programmer: Receiver {
331 | let name: String
332 |
333 | init(name: String) {
334 | self.name = name
335 | }
336 |
337 | func receive(message: String) {
338 | print("\(name) received: \(message)")
339 | }
340 | }
341 |
342 | final class MessageMediator: Sender {
343 | internal var recipients: [Programmer] = []
344 |
345 | func add(recipient: Programmer) {
346 | recipients.append(recipient)
347 | }
348 |
349 | func send(message: String) {
350 | for recipient in recipients {
351 | recipient.receive(message: message)
352 | }
353 | }
354 | }
355 |
356 | /*:
357 | ### Usage
358 | */
359 | func spamMonster(message: String, worker: MessageMediator) {
360 | worker.send(message: message)
361 | }
362 |
363 | let messagesMediator = MessageMediator()
364 |
365 | let user0 = Programmer(name: "Linus Torvalds")
366 | let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
367 | messagesMediator.add(recipient: user0)
368 | messagesMediator.add(recipient: user1)
369 |
370 | spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
371 |
372 | /*:
373 | 💾 Memento
374 | ----------
375 |
376 | The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
377 |
378 | ### Example
379 | */
380 | typealias Memento = [String: String]
381 | /*:
382 | Originator
383 | */
384 | protocol MementoConvertible {
385 | var memento: Memento { get }
386 | init?(memento: Memento)
387 | }
388 |
389 | struct GameState: MementoConvertible {
390 |
391 | private enum Keys {
392 | static let chapter = "com.valve.halflife.chapter"
393 | static let weapon = "com.valve.halflife.weapon"
394 | }
395 |
396 | var chapter: String
397 | var weapon: String
398 |
399 | init(chapter: String, weapon: String) {
400 | self.chapter = chapter
401 | self.weapon = weapon
402 | }
403 |
404 | init?(memento: Memento) {
405 | guard let mementoChapter = memento[Keys.chapter],
406 | let mementoWeapon = memento[Keys.weapon] else {
407 | return nil
408 | }
409 |
410 | chapter = mementoChapter
411 | weapon = mementoWeapon
412 | }
413 |
414 | var memento: Memento {
415 | return [ Keys.chapter: chapter, Keys.weapon: weapon ]
416 | }
417 | }
418 | /*:
419 | Caretaker
420 | */
421 | enum CheckPoint {
422 |
423 | private static let defaults = UserDefaults.standard
424 |
425 | static func save(_ state: MementoConvertible, saveName: String) {
426 | defaults.set(state.memento, forKey: saveName)
427 | defaults.synchronize()
428 | }
429 |
430 | static func restore(saveName: String) -> Any? {
431 | return defaults.object(forKey: saveName)
432 | }
433 | }
434 | /*:
435 | ### Usage
436 | */
437 | var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
438 |
439 | gameState.chapter = "Anomalous Materials"
440 | gameState.weapon = "Glock 17"
441 | CheckPoint.save(gameState, saveName: "gameState1")
442 |
443 | gameState.chapter = "Unforeseen Consequences"
444 | gameState.weapon = "MP5"
445 | CheckPoint.save(gameState, saveName: "gameState2")
446 |
447 | gameState.chapter = "Office Complex"
448 | gameState.weapon = "Crossbow"
449 | CheckPoint.save(gameState, saveName: "gameState3")
450 |
451 | if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
452 | let finalState = GameState(memento: memento)
453 | dump(finalState)
454 | }
455 | /*:
456 | 👓 Observer
457 | -----------
458 |
459 | The observer pattern is used to allow an object to publish changes to its state.
460 | Other objects subscribe to be immediately notified of any changes.
461 |
462 | ### Example
463 | */
464 | protocol PropertyObserver : class {
465 | func willChange(propertyName: String, newPropertyValue: Any?)
466 | func didChange(propertyName: String, oldPropertyValue: Any?)
467 | }
468 |
469 | final class TestChambers {
470 |
471 | weak var observer:PropertyObserver?
472 |
473 | private let testChamberNumberName = "testChamberNumber"
474 |
475 | var testChamberNumber: Int = 0 {
476 | willSet(newValue) {
477 | observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
478 | }
479 | didSet {
480 | observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
481 | }
482 | }
483 | }
484 |
485 | final class Observer : PropertyObserver {
486 | func willChange(propertyName: String, newPropertyValue: Any?) {
487 | if newPropertyValue as? Int == 1 {
488 | print("Okay. Look. We both said a lot of things that you're going to regret.")
489 | }
490 | }
491 |
492 | func didChange(propertyName: String, oldPropertyValue: Any?) {
493 | if oldPropertyValue as? Int == 0 {
494 | print("Sorry about the mess. I've really let the place go since you killed me.")
495 | }
496 | }
497 | }
498 | /*:
499 | ### Usage
500 | */
501 | var observerInstance = Observer()
502 | var testChambers = TestChambers()
503 | testChambers.observer = observerInstance
504 | testChambers.testChamberNumber += 1
505 | /*:
506 | 🐉 State
507 | ---------
508 |
509 | The state pattern is used to alter the behaviour of an object as its internal state changes.
510 | The pattern allows the class for an object to apparently change at run-time.
511 |
512 | ### Example
513 | */
514 | final class Context {
515 | private var state: State = UnauthorizedState()
516 |
517 | var isAuthorized: Bool {
518 | get { return state.isAuthorized(context: self) }
519 | }
520 |
521 | var userId: String? {
522 | get { return state.userId(context: self) }
523 | }
524 |
525 | func changeStateToAuthorized(userId: String) {
526 | state = AuthorizedState(userId: userId)
527 | }
528 |
529 | func changeStateToUnauthorized() {
530 | state = UnauthorizedState()
531 | }
532 | }
533 |
534 | protocol State {
535 | func isAuthorized(context: Context) -> Bool
536 | func userId(context: Context) -> String?
537 | }
538 |
539 | class UnauthorizedState: State {
540 | func isAuthorized(context: Context) -> Bool { return false }
541 |
542 | func userId(context: Context) -> String? { return nil }
543 | }
544 |
545 | class AuthorizedState: State {
546 | let userId: String
547 |
548 | init(userId: String) { self.userId = userId }
549 |
550 | func isAuthorized(context: Context) -> Bool { return true }
551 |
552 | func userId(context: Context) -> String? { return userId }
553 | }
554 | /*:
555 | ### Usage
556 | */
557 | let userContext = Context()
558 | (userContext.isAuthorized, userContext.userId)
559 | userContext.changeStateToAuthorized(userId: "admin")
560 | (userContext.isAuthorized, userContext.userId) // now logged in as "admin"
561 | userContext.changeStateToUnauthorized()
562 | (userContext.isAuthorized, userContext.userId)
563 | /*:
564 | 💡 Strategy
565 | -----------
566 |
567 | The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
568 |
569 | ### Example
570 | */
571 |
572 | struct TestSubject {
573 | let pupilDiameter: Double
574 | let blushResponse: Double
575 | let isOrganic: Bool
576 | }
577 |
578 | protocol RealnessTesting: AnyObject {
579 | func testRealness(_ testSubject: TestSubject) -> Bool
580 | }
581 |
582 | final class VoightKampffTest: RealnessTesting {
583 | func testRealness(_ testSubject: TestSubject) -> Bool {
584 | return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
585 | }
586 | }
587 |
588 | final class GeneticTest: RealnessTesting {
589 | func testRealness(_ testSubject: TestSubject) -> Bool {
590 | return testSubject.isOrganic
591 | }
592 | }
593 |
594 | final class BladeRunner {
595 | private let strategy: RealnessTesting
596 |
597 | init(test: RealnessTesting) {
598 | self.strategy = test
599 | }
600 |
601 | func testIfAndroid(_ testSubject: TestSubject) -> Bool {
602 | return !strategy.testRealness(testSubject)
603 | }
604 | }
605 |
606 | /*:
607 | ### Usage
608 | */
609 |
610 | let rachel = TestSubject(pupilDiameter: 30.2,
611 | blushResponse: 0.3,
612 | isOrganic: false)
613 |
614 | // Deckard is using a traditional test
615 | let deckard = BladeRunner(test: VoightKampffTest())
616 | let isRachelAndroid = deckard.testIfAndroid(rachel)
617 |
618 | // Gaff is using a very precise method
619 | let gaff = BladeRunner(test: GeneticTest())
620 | let isDeckardAndroid = gaff.testIfAndroid(rachel)
621 | /*:
622 | 📝 Template Method
623 | -----------
624 |
625 | The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.
626 |
627 | ### Example
628 | */
629 | protocol Garden {
630 | func prepareSoil()
631 | func plantSeeds()
632 | func waterPlants()
633 | func prepareGarden()
634 | }
635 |
636 | extension Garden {
637 |
638 | func prepareGarden() {
639 | prepareSoil()
640 | plantSeeds()
641 | waterPlants()
642 | }
643 | }
644 |
645 | final class RoseGarden: Garden {
646 |
647 | func prepare() {
648 | prepareGarden()
649 | }
650 |
651 | func prepareSoil() {
652 | print ("prepare soil for rose garden")
653 | }
654 |
655 | func plantSeeds() {
656 | print ("plant seeds for rose garden")
657 | }
658 |
659 | func waterPlants() {
660 | print ("water the rose garden")
661 | }
662 | }
663 |
664 | /*:
665 | ### Usage
666 | */
667 |
668 | let roseGarden = RoseGarden()
669 | roseGarden.prepare()
670 | /*:
671 | 🏃 Visitor
672 | ----------
673 |
674 | The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
675 |
676 | ### Example
677 | */
678 | protocol PlanetVisitor {
679 | func visit(planet: PlanetAlderaan)
680 | func visit(planet: PlanetCoruscant)
681 | func visit(planet: PlanetTatooine)
682 | func visit(planet: MoonJedha)
683 | }
684 |
685 | protocol Planet {
686 | func accept(visitor: PlanetVisitor)
687 | }
688 |
689 | final class MoonJedha: Planet {
690 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
691 | }
692 |
693 | final class PlanetAlderaan: Planet {
694 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
695 | }
696 |
697 | final class PlanetCoruscant: Planet {
698 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
699 | }
700 |
701 | final class PlanetTatooine: Planet {
702 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
703 | }
704 |
705 | final class NameVisitor: PlanetVisitor {
706 | var name = ""
707 |
708 | func visit(planet: PlanetAlderaan) { name = "Alderaan" }
709 | func visit(planet: PlanetCoruscant) { name = "Coruscant" }
710 | func visit(planet: PlanetTatooine) { name = "Tatooine" }
711 | func visit(planet: MoonJedha) { name = "Jedha" }
712 | }
713 |
714 | /*:
715 | ### Usage
716 | */
717 | let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
718 |
719 | let names = planets.map { (planet: Planet) -> String in
720 | let visitor = NameVisitor()
721 | planet.accept(visitor: visitor)
722 |
723 | return visitor.name
724 | }
725 |
726 | names
727 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | Creational
4 | ==========
5 |
6 | > In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
7 | >
8 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)
9 |
10 | ## Table of Contents
11 |
12 | * [Behavioral](Behavioral)
13 | * [Creational](Creational)
14 | * [Structural](Structural)
15 |
16 | */
17 | import Foundation
18 | /*:
19 | 🌰 Abstract Factory
20 | -------------------
21 |
22 | The abstract factory pattern is used to provide a client with a set of related or dependant objects.
23 | The "family" of objects created by the factory are determined at run-time.
24 |
25 | ### Example
26 |
27 | Protocols
28 | */
29 |
30 | protocol BurgerDescribing {
31 | var ingredients: [String] { get }
32 | }
33 |
34 | struct CheeseBurger: BurgerDescribing {
35 | let ingredients: [String]
36 | }
37 |
38 | protocol BurgerMaking {
39 | func make() -> BurgerDescribing
40 | }
41 |
42 | // Number implementations with factory methods
43 |
44 | final class BigKahunaBurger: BurgerMaking {
45 | func make() -> BurgerDescribing {
46 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
47 | }
48 | }
49 |
50 | final class JackInTheBox: BurgerMaking {
51 | func make() -> BurgerDescribing {
52 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
53 | }
54 | }
55 |
56 | /*:
57 | Abstract factory
58 | */
59 |
60 | enum BurgerFactoryType: BurgerMaking {
61 |
62 | case bigKahuna
63 | case jackInTheBox
64 |
65 | func make() -> BurgerDescribing {
66 | switch self {
67 | case .bigKahuna:
68 | return BigKahunaBurger().make()
69 | case .jackInTheBox:
70 | return JackInTheBox().make()
71 | }
72 | }
73 | }
74 | /*:
75 | ### Usage
76 | */
77 | let bigKahuna = BurgerFactoryType.bigKahuna.make()
78 | let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
79 | /*:
80 | 👷 Builder
81 | ----------
82 |
83 | The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm.
84 | An external class controls the construction algorithm.
85 |
86 | ### Example
87 | */
88 | final class DeathStarBuilder {
89 |
90 | var x: Double?
91 | var y: Double?
92 | var z: Double?
93 |
94 | typealias BuilderClosure = (DeathStarBuilder) -> ()
95 |
96 | init(buildClosure: BuilderClosure) {
97 | buildClosure(self)
98 | }
99 | }
100 |
101 | struct DeathStar : CustomStringConvertible {
102 |
103 | let x: Double
104 | let y: Double
105 | let z: Double
106 |
107 | init?(builder: DeathStarBuilder) {
108 |
109 | if let x = builder.x, let y = builder.y, let z = builder.z {
110 | self.x = x
111 | self.y = y
112 | self.z = z
113 | } else {
114 | return nil
115 | }
116 | }
117 |
118 | var description:String {
119 | return "Death Star at (x:\(x) y:\(y) z:\(z))"
120 | }
121 | }
122 | /*:
123 | ### Usage
124 | */
125 | let empire = DeathStarBuilder { builder in
126 | builder.x = 0.1
127 | builder.y = 0.2
128 | builder.z = 0.3
129 | }
130 |
131 | let deathStar = DeathStar(builder:empire)
132 | /*:
133 | 🏭 Factory Method
134 | -----------------
135 |
136 | The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
137 |
138 | ### Example
139 | */
140 | protocol CurrencyDescribing {
141 | var symbol: String { get }
142 | var code: String { get }
143 | }
144 |
145 | final class Euro: CurrencyDescribing {
146 | var symbol: String {
147 | return "€"
148 | }
149 |
150 | var code: String {
151 | return "EUR"
152 | }
153 | }
154 |
155 | final class UnitedStatesDolar: CurrencyDescribing {
156 | var symbol: String {
157 | return "$"
158 | }
159 |
160 | var code: String {
161 | return "USD"
162 | }
163 | }
164 |
165 | enum Country {
166 | case unitedStates
167 | case spain
168 | case uk
169 | case greece
170 | }
171 |
172 | enum CurrencyFactory {
173 | static func currency(for country: Country) -> CurrencyDescribing? {
174 |
175 | switch country {
176 | case .spain, .greece:
177 | return Euro()
178 | case .unitedStates:
179 | return UnitedStatesDolar()
180 | default:
181 | return nil
182 | }
183 |
184 | }
185 | }
186 | /*:
187 | ### Usage
188 | */
189 | let noCurrencyCode = "No Currency Code Available"
190 |
191 | CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
192 | CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
193 | CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
194 | CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
195 | /*:
196 | 🔂 Monostate
197 | ------------
198 |
199 | The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints.
200 | So in that case, monostate saves the state as static instead of the entire instance as a singleton.
201 | [SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
202 |
203 | ### Example:
204 | */
205 | class Settings {
206 |
207 | enum Theme {
208 | case `default`
209 | case old
210 | case new
211 | }
212 |
213 | private static var theme: Theme?
214 |
215 | var currentTheme: Theme {
216 | get { Settings.theme ?? .default }
217 | set(newTheme) { Settings.theme = newTheme }
218 | }
219 | }
220 | /*:
221 | ### Usage:
222 | */
223 |
224 | import SwiftUI
225 |
226 | // When change the theme
227 | let settings = Settings() // Starts using theme .old
228 | settings.currentTheme = .new // Change theme to .new
229 |
230 | // On screen 1
231 | let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
232 |
233 | // On screen 2
234 | let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
235 | /*:
236 | 🃏 Prototype
237 | ------------
238 |
239 | The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
240 | This practise is particularly useful when the construction of a new object is inefficient.
241 |
242 | ### Example
243 | */
244 | class MoonWorker {
245 |
246 | let name: String
247 | var health: Int = 100
248 |
249 | init(name: String) {
250 | self.name = name
251 | }
252 |
253 | func clone() -> MoonWorker {
254 | return MoonWorker(name: name)
255 | }
256 | }
257 | /*:
258 | ### Usage
259 | */
260 | let prototype = MoonWorker(name: "Sam Bell")
261 |
262 | var bell1 = prototype.clone()
263 | bell1.health = 12
264 |
265 | var bell2 = prototype.clone()
266 | bell2.health = 23
267 |
268 | var bell3 = prototype.clone()
269 | bell3.health = 0
270 | /*:
271 | 💍 Singleton
272 | ------------
273 |
274 | The singleton pattern ensures that only one object of a particular class is ever created.
275 | All further references to objects of the singleton class refer to the same underlying instance.
276 | There are very few applications, do not overuse this pattern!
277 |
278 | ### Example:
279 | */
280 | final class ElonMusk {
281 |
282 | static let shared = ElonMusk()
283 |
284 | private init() {
285 | // Private initialization to ensure just one instance is created.
286 | }
287 | }
288 | /*:
289 | ### Usage:
290 | */
291 | let elon = ElonMusk.shared // There is only one Elon Musk folks.
292 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Index.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | Design Patterns implemented in Swift 5.0
4 | ========================================
5 |
6 | A short cheat-sheet with Xcode 10.2 Playground ([Design-Patterns.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns.playground.zip)).
7 |
8 | ### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)
9 |
10 | 👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)
11 |
12 | 👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。
13 |
14 | 🚀 How to generate README, Playground and zip from source: [GENERATE.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/GENERATE.md)
15 |
16 | ## Table of Contents
17 |
18 | * [Behavioral](Behavioral)
19 | * [Creational](Creational)
20 | * [Structural](Structural)
21 |
22 | */
23 | import Foundation
24 |
25 | print("Welcome!")
26 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Structural.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | Structural
4 | ==========
5 |
6 | >In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
7 | >
8 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)
9 |
10 | ## Table of Contents
11 |
12 | * [Behavioral](Behavioral)
13 | * [Creational](Creational)
14 | * [Structural](Structural)
15 |
16 | */
17 | import Foundation
18 | /*:
19 | 🔌 Adapter
20 | ----------
21 |
22 | The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
23 |
24 | ### Example
25 | */
26 | protocol NewDeathStarSuperLaserAiming {
27 | var angleV: Double { get }
28 | var angleH: Double { get }
29 | }
30 | /*:
31 | **Adaptee**
32 | */
33 | struct OldDeathStarSuperlaserTarget {
34 | let angleHorizontal: Float
35 | let angleVertical: Float
36 |
37 | init(angleHorizontal: Float, angleVertical: Float) {
38 | self.angleHorizontal = angleHorizontal
39 | self.angleVertical = angleVertical
40 | }
41 | }
42 | /*:
43 | **Adapter**
44 | */
45 | struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
46 |
47 | private let target: OldDeathStarSuperlaserTarget
48 |
49 | var angleV: Double {
50 | return Double(target.angleVertical)
51 | }
52 |
53 | var angleH: Double {
54 | return Double(target.angleHorizontal)
55 | }
56 |
57 | init(_ target: OldDeathStarSuperlaserTarget) {
58 | self.target = target
59 | }
60 | }
61 | /*:
62 | ### Usage
63 | */
64 | let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
65 | let newFormat = NewDeathStarSuperlaserTarget(target)
66 |
67 | newFormat.angleH
68 | newFormat.angleV
69 | /*:
70 | 🌉 Bridge
71 | ----------
72 |
73 | The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
74 |
75 | ### Example
76 | */
77 | protocol Switch {
78 | var appliance: Appliance { get set }
79 | func turnOn()
80 | }
81 |
82 | protocol Appliance {
83 | func run()
84 | }
85 |
86 | final class RemoteControl: Switch {
87 | var appliance: Appliance
88 |
89 | func turnOn() {
90 | self.appliance.run()
91 | }
92 |
93 | init(appliance: Appliance) {
94 | self.appliance = appliance
95 | }
96 | }
97 |
98 | final class TV: Appliance {
99 | func run() {
100 | print("tv turned on");
101 | }
102 | }
103 |
104 | final class VacuumCleaner: Appliance {
105 | func run() {
106 | print("vacuum cleaner turned on")
107 | }
108 | }
109 | /*:
110 | ### Usage
111 | */
112 | let tvRemoteControl = RemoteControl(appliance: TV())
113 | tvRemoteControl.turnOn()
114 |
115 | let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
116 | fancyVacuumCleanerRemoteControl.turnOn()
117 | /*:
118 | 🌿 Composite
119 | -------------
120 |
121 | The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
122 |
123 | ### Example
124 |
125 | Component
126 | */
127 | protocol Shape {
128 | func draw(fillColor: String)
129 | }
130 | /*:
131 | Leafs
132 | */
133 | final class Square: Shape {
134 | func draw(fillColor: String) {
135 | print("Drawing a Square with color \(fillColor)")
136 | }
137 | }
138 |
139 | final class Circle: Shape {
140 | func draw(fillColor: String) {
141 | print("Drawing a circle with color \(fillColor)")
142 | }
143 | }
144 |
145 | /*:
146 | Composite
147 | */
148 | final class Whiteboard: Shape {
149 |
150 | private lazy var shapes = [Shape]()
151 |
152 | init(_ shapes: Shape...) {
153 | self.shapes = shapes
154 | }
155 |
156 | func draw(fillColor: String) {
157 | for shape in self.shapes {
158 | shape.draw(fillColor: fillColor)
159 | }
160 | }
161 | }
162 | /*:
163 | ### Usage:
164 | */
165 | var whiteboard = Whiteboard(Circle(), Square())
166 | whiteboard.draw(fillColor: "Red")
167 | /*:
168 | 🍧 Decorator
169 | ------------
170 |
171 | The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class.
172 | This provides a flexible alternative to using inheritance to modify behaviour.
173 |
174 | ### Example
175 | */
176 | protocol CostHaving {
177 | var cost: Double { get }
178 | }
179 |
180 | protocol IngredientsHaving {
181 | var ingredients: [String] { get }
182 | }
183 |
184 | typealias BeverageDataHaving = CostHaving & IngredientsHaving
185 |
186 | struct SimpleCoffee: BeverageDataHaving {
187 | let cost: Double = 1.0
188 | let ingredients = ["Water", "Coffee"]
189 | }
190 |
191 | protocol BeverageHaving: BeverageDataHaving {
192 | var beverage: BeverageDataHaving { get }
193 | }
194 |
195 | struct Milk: BeverageHaving {
196 |
197 | let beverage: BeverageDataHaving
198 |
199 | var cost: Double {
200 | return beverage.cost + 0.5
201 | }
202 |
203 | var ingredients: [String] {
204 | return beverage.ingredients + ["Milk"]
205 | }
206 | }
207 |
208 | struct WhipCoffee: BeverageHaving {
209 |
210 | let beverage: BeverageDataHaving
211 |
212 | var cost: Double {
213 | return beverage.cost + 0.5
214 | }
215 |
216 | var ingredients: [String] {
217 | return beverage.ingredients + ["Whip"]
218 | }
219 | }
220 | /*:
221 | ### Usage:
222 | */
223 | var someCoffee: BeverageDataHaving = SimpleCoffee()
224 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
225 | someCoffee = Milk(beverage: someCoffee)
226 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
227 | someCoffee = WhipCoffee(beverage: someCoffee)
228 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
229 | /*:
230 | 🎁 Façade
231 | ---------
232 |
233 | The facade pattern is used to define a simplified interface to a more complex subsystem.
234 |
235 | ### Example
236 | */
237 | final class Defaults {
238 |
239 | private let defaults: UserDefaults
240 |
241 | init(defaults: UserDefaults = .standard) {
242 | self.defaults = defaults
243 | }
244 |
245 | subscript(key: String) -> String? {
246 | get {
247 | return defaults.string(forKey: key)
248 | }
249 |
250 | set {
251 | defaults.set(newValue, forKey: key)
252 | }
253 | }
254 | }
255 | /*:
256 | ### Usage
257 | */
258 | let storage = Defaults()
259 |
260 | // Store
261 | storage["Bishop"] = "Disconnect me. I’d rather be nothing"
262 |
263 | // Read
264 | storage["Bishop"]
265 | /*:
266 | ## 🍃 Flyweight
267 | The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
268 | ### Example
269 | */
270 | // Instances of SpecialityCoffee will be the Flyweights
271 | struct SpecialityCoffee {
272 | let origin: String
273 | }
274 |
275 | protocol CoffeeSearching {
276 | func search(origin: String) -> SpecialityCoffee?
277 | }
278 |
279 | // Menu acts as a factory and cache for SpecialityCoffee flyweight objects
280 | final class Menu: CoffeeSearching {
281 |
282 | private var coffeeAvailable: [String: SpecialityCoffee] = [:]
283 |
284 | func search(origin: String) -> SpecialityCoffee? {
285 | if coffeeAvailable.index(forKey: origin) == nil {
286 | coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
287 | }
288 |
289 | return coffeeAvailable[origin]
290 | }
291 | }
292 |
293 | final class CoffeeShop {
294 | private var orders: [Int: SpecialityCoffee] = [:]
295 | private let menu: CoffeeSearching
296 |
297 | init(menu: CoffeeSearching) {
298 | self.menu = menu
299 | }
300 |
301 | func takeOrder(origin: String, table: Int) {
302 | orders[table] = menu.search(origin: origin)
303 | }
304 |
305 | func serve() {
306 | for (table, origin) in orders {
307 | print("Serving \(origin) to table \(table)")
308 | }
309 | }
310 | }
311 | /*:
312 | ### Usage
313 | */
314 | let coffeeShop = CoffeeShop(menu: Menu())
315 |
316 | coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
317 | coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
318 |
319 | coffeeShop.serve()
320 | /*:
321 | ☔ Protection Proxy
322 | ------------------
323 |
324 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
325 | Protection proxy is restricting access.
326 |
327 | ### Example
328 | */
329 | protocol DoorOpening {
330 | func open(doors: String) -> String
331 | }
332 |
333 | final class HAL9000: DoorOpening {
334 | func open(doors: String) -> String {
335 | return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
336 | }
337 | }
338 |
339 | final class CurrentComputer: DoorOpening {
340 | private var computer: HAL9000!
341 |
342 | func authenticate(password: String) -> Bool {
343 |
344 | guard password == "pass" else {
345 | return false
346 | }
347 |
348 | computer = HAL9000()
349 |
350 | return true
351 | }
352 |
353 | func open(doors: String) -> String {
354 |
355 | guard computer != nil else {
356 | return "Access Denied. I'm afraid I can't do that."
357 | }
358 |
359 | return computer.open(doors: doors)
360 | }
361 | }
362 | /*:
363 | ### Usage
364 | */
365 | let computer = CurrentComputer()
366 | let podBay = "Pod Bay Doors"
367 |
368 | computer.open(doors: podBay)
369 |
370 | computer.authenticate(password: "pass")
371 | computer.open(doors: podBay)
372 | /*:
373 | 🍬 Virtual Proxy
374 | ----------------
375 |
376 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
377 | Virtual proxy is used for loading object on demand.
378 |
379 | ### Example
380 | */
381 | protocol HEVSuitMedicalAid {
382 | func administerMorphine() -> String
383 | }
384 |
385 | final class HEVSuit: HEVSuitMedicalAid {
386 | func administerMorphine() -> String {
387 | return "Morphine administered."
388 | }
389 | }
390 |
391 | final class HEVSuitHumanInterface: HEVSuitMedicalAid {
392 |
393 | lazy private var physicalSuit: HEVSuit = HEVSuit()
394 |
395 | func administerMorphine() -> String {
396 | return physicalSuit.administerMorphine()
397 | }
398 | }
399 | /*:
400 | ### Usage
401 | */
402 | let humanInterface = HEVSuitHumanInterface()
403 | humanInterface.administerMorphine()
404 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | - [ ] Read [CONTRIBUTING.md]](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md])
2 | - [ ] Added description
3 | - [ ] Linked to and/or created issue
--------------------------------------------------------------------------------
/generate-playground-cn.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Note: I think this part is absolute garbage but it's a snapshot of my current skills with Bash.
4 | # Would love to rewrite it in Swift soon.
5 |
6 | combineSwiftCN() {
7 | cat source-cn/startComment > $2
8 | cat $1/header.md >> $2
9 | cat source-cn/contents.md >> $2
10 | cat source-cn/endComment >> $2
11 | cat source-cn/imports.swift >> $2
12 | cat $1/*.swift >> $2
13 | { rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
14 | }
15 |
16 | move() {
17 | mv $1.swift Design-Patterns-CN.playground/Pages/$1.xcplaygroundpage/Contents.swift
18 | }
19 |
20 | playground() {
21 | combineSwiftCN source-cn/$1 $1.swift
22 | move $1
23 | }
24 |
25 | combineMarkdown() {
26 | cat $1/header.md > $2
27 |
28 | { rm $2 && awk '{gsub("\\*/", "", $0); print}' > $2; } < $2
29 | { rm $2 && awk '{gsub("/\\*:", "", $0); print}' > $2; } < $2
30 |
31 | cat source-cn/startSwiftCode >> $2
32 | cat $1/*.swift >> $2
33 |
34 | { rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
35 | { rm $2 && awk '{gsub("\\*/", "\n```swift", $0); print}' > $2; } < $2
36 | { rm $2 && awk '{gsub("/\\*:", "```\n", $0); print}' > $2; } < $2
37 |
38 | cat source-cn/endSwiftCode >> $2
39 |
40 | { rm $2 && awk '{gsub("```swift```", "", $0); print}' > $2; } < $2
41 |
42 | cat $2 >> README-CN.md
43 | rm $2
44 | }
45 |
46 | readme() {
47 | combineMarkdown source-cn/$1 $1.md
48 | }
49 |
50 | playground Index
51 | playground Behavioral
52 | playground Creational
53 | playground Structural
54 |
55 | zip -r -X Design-Patterns-CN.playground.zip ./Design-Patterns-CN.playground
56 |
57 | echo "" > README-CN.md
58 |
59 | readme Index
60 | cat source-cn/contentsReadme.md >> README-CN.md
61 | readme Behavioral
62 | readme Creational
63 | readme Structural
64 | cat source-cn/footer.md >> README-CN.md
--------------------------------------------------------------------------------
/generate-playground.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Note: I think this part is absolute garbage but it's a snapshot of my current skills with Bash.
4 | # Would love to rewrite it in Swift soon.
5 |
6 | combineSwift() {
7 | cat source/startComment > $2
8 | cat $1/header.md >> $2
9 | cat source/contents.md >> $2
10 | cat source/endComment >> $2
11 | cat source/imports.swift >> $2
12 | cat $1/*.swift >> $2
13 | { rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
14 | }
15 |
16 | move() {
17 | mv $1.swift Design-Patterns.playground/Pages/$1.xcplaygroundpage/Contents.swift
18 | }
19 |
20 | playground() {
21 | combineSwift source/$1 $1.swift
22 | move $1
23 | }
24 |
25 | combineMarkdown() {
26 | cat $1/header.md > $2
27 |
28 | { rm $2 && awk '{gsub("\\*/", "", $0); print}' > $2; } < $2
29 | { rm $2 && awk '{gsub("/\\*:", "", $0); print}' > $2; } < $2
30 |
31 | cat source/startSwiftCode >> $2
32 | cat $1/*.swift >> $2
33 |
34 | { rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
35 | { rm $2 && awk '{gsub("\\*/", "\n```swift", $0); print}' > $2; } < $2
36 | { rm $2 && awk '{gsub("/\\*:", "```\n", $0); print}' > $2; } < $2
37 |
38 | cat source/endSwiftCode >> $2
39 |
40 | { rm $2 && awk '{gsub("```swift```", "", $0); print}' > $2; } < $2
41 |
42 | cat $2 >> README.md
43 | rm $2
44 | }
45 |
46 | readme() {
47 | combineMarkdown source/$1 $1.md
48 | }
49 |
50 | playground Index
51 | playground Behavioral
52 | playground Creational
53 | playground Structural
54 |
55 | zip -r -X Design-Patterns.playground.zip ./Design-Patterns.playground
56 |
57 | echo "" > README.md
58 |
59 | readme Index
60 | cat source/contentsReadme.md >> README.md
61 | readme Behavioral
62 | readme Creational
63 | readme Structural
64 | cat source/footer.md >> README.md
--------------------------------------------------------------------------------
/source-cn/Index/header.md:
--------------------------------------------------------------------------------
1 |
2 | 设计模式(Swift 5.0 实现)
3 | ======================
4 |
5 | ([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).
6 |
7 | 👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。
8 |
9 | 🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。
10 |
--------------------------------------------------------------------------------
/source-cn/Index/welcome.swift:
--------------------------------------------------------------------------------
1 |
2 | print("您好!")
3 |
--------------------------------------------------------------------------------
/source-cn/behavioral/chain_of_responsibility.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🐝 责任链(Chain Of Responsibility)
3 | ------------------------------
4 |
5 | 责任链模式在面向对象程式设计里是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。
6 |
7 | ### 示例:
8 | */
9 |
10 | protocol Withdrawing {
11 | func withdraw(amount: Int) -> Bool
12 | }
13 |
14 | final class MoneyPile: Withdrawing {
15 |
16 | let value: Int
17 | var quantity: Int
18 | var next: Withdrawing?
19 |
20 | init(value: Int, quantity: Int, next: Withdrawing?) {
21 | self.value = value
22 | self.quantity = quantity
23 | self.next = next
24 | }
25 |
26 | func withdraw(amount: Int) -> Bool {
27 |
28 | var amount = amount
29 |
30 | func canTakeSomeBill(want: Int) -> Bool {
31 | return (want / self.value) > 0
32 | }
33 |
34 | var quantity = self.quantity
35 |
36 | while canTakeSomeBill(want: amount) {
37 |
38 | if quantity == 0 {
39 | break
40 | }
41 |
42 | amount -= self.value
43 | quantity -= 1
44 | }
45 |
46 | guard amount > 0 else {
47 | return true
48 | }
49 |
50 | if let next = self.next {
51 | return next.withdraw(amount: amount)
52 | }
53 |
54 | return false
55 | }
56 | }
57 |
58 | final class ATM: Withdrawing {
59 |
60 | private var hundred: Withdrawing
61 | private var fifty: Withdrawing
62 | private var twenty: Withdrawing
63 | private var ten: Withdrawing
64 |
65 | private var startPile: Withdrawing {
66 | return self.hundred
67 | }
68 |
69 | init(hundred: Withdrawing,
70 | fifty: Withdrawing,
71 | twenty: Withdrawing,
72 | ten: Withdrawing) {
73 |
74 | self.hundred = hundred
75 | self.fifty = fifty
76 | self.twenty = twenty
77 | self.ten = ten
78 | }
79 |
80 | func withdraw(amount: Int) -> Bool {
81 | return startPile.withdraw(amount: amount)
82 | }
83 | }
84 | /*:
85 | ### 用法
86 | */
87 | // 创建一系列的钱堆,并将其链接起来:10<20<50<100
88 | let ten = MoneyPile(value: 10, quantity: 6, next: nil)
89 | let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
90 | let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
91 | let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
92 |
93 | // 创建 ATM 实例
94 | var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
95 | atm.withdraw(amount: 310) // Cannot because ATM has only 300
96 | atm.withdraw(amount: 100) // Can withdraw - 1x100
97 |
--------------------------------------------------------------------------------
/source-cn/behavioral/command.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 👫 命令(Command)
3 | ------------
4 | 命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:
5 | * 重复多次
6 | * 取消(如果该对象有实现的话)
7 | * 取消后又再重做
8 | ### 示例:
9 | */
10 | protocol DoorCommand {
11 | func execute() -> String
12 | }
13 |
14 | final class OpenCommand: DoorCommand {
15 | let doors:String
16 |
17 | required init(doors: String) {
18 | self.doors = doors
19 | }
20 |
21 | func execute() -> String {
22 | return "Opened \(doors)"
23 | }
24 | }
25 |
26 | final class CloseCommand: DoorCommand {
27 | let doors:String
28 |
29 | required init(doors: String) {
30 | self.doors = doors
31 | }
32 |
33 | func execute() -> String {
34 | return "Closed \(doors)"
35 | }
36 | }
37 |
38 | final class HAL9000DoorsOperations {
39 | let openCommand: DoorCommand
40 | let closeCommand: DoorCommand
41 |
42 | init(doors: String) {
43 | self.openCommand = OpenCommand(doors:doors)
44 | self.closeCommand = CloseCommand(doors:doors)
45 | }
46 |
47 | func close() -> String {
48 | return closeCommand.execute()
49 | }
50 |
51 | func open() -> String {
52 | return openCommand.execute()
53 | }
54 | }
55 | /*:
56 | ### 用法
57 | */
58 | let podBayDoors = "Pod Bay Doors"
59 | let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
60 |
61 | doorModule.open()
62 | doorModule.close()
63 |
--------------------------------------------------------------------------------
/source-cn/behavioral/header.md:
--------------------------------------------------------------------------------
1 |
2 | 行为型模式
3 | ========
4 |
5 | >在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。
6 | >
7 | >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
8 |
--------------------------------------------------------------------------------
/source-cn/behavioral/interpreter.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🎶 解释器(Interpreter)
3 | ------------------
4 |
5 | 给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
6 |
7 | ### 示例:
8 | */
9 |
10 | protocol IntegerExpression {
11 | func evaluate(_ context: IntegerContext) -> Int
12 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
13 | func copied() -> IntegerExpression
14 | }
15 |
16 | final class IntegerContext {
17 | private var data: [Character:Int] = [:]
18 |
19 | func lookup(name: Character) -> Int {
20 | return self.data[name]!
21 | }
22 |
23 | func assign(expression: IntegerVariableExpression, value: Int) {
24 | self.data[expression.name] = value
25 | }
26 | }
27 |
28 | final class IntegerVariableExpression: IntegerExpression {
29 | let name: Character
30 |
31 | init(name: Character) {
32 | self.name = name
33 | }
34 |
35 | func evaluate(_ context: IntegerContext) -> Int {
36 | return context.lookup(name: self.name)
37 | }
38 |
39 | func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
40 | if name == self.name {
41 | return integerExpression.copied()
42 | } else {
43 | return IntegerVariableExpression(name: self.name)
44 | }
45 | }
46 |
47 | func copied() -> IntegerExpression {
48 | return IntegerVariableExpression(name: self.name)
49 | }
50 | }
51 |
52 | final class AddExpression: IntegerExpression {
53 | private var operand1: IntegerExpression
54 | private var operand2: IntegerExpression
55 |
56 | init(op1: IntegerExpression, op2: IntegerExpression) {
57 | self.operand1 = op1
58 | self.operand2 = op2
59 | }
60 |
61 | func evaluate(_ context: IntegerContext) -> Int {
62 | return self.operand1.evaluate(context) + self.operand2.evaluate(context)
63 | }
64 |
65 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
66 | return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
67 | op2: operand2.replace(character: character, integerExpression: integerExpression))
68 | }
69 |
70 | func copied() -> IntegerExpression {
71 | return AddExpression(op1: self.operand1, op2: self.operand2)
72 | }
73 | }
74 | /*:
75 | ### 用法
76 | */
77 | var context = IntegerContext()
78 |
79 | var a = IntegerVariableExpression(name: "A")
80 | var b = IntegerVariableExpression(name: "B")
81 | var c = IntegerVariableExpression(name: "C")
82 |
83 | var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
84 |
85 | context.assign(expression: a, value: 2)
86 | context.assign(expression: b, value: 1)
87 | context.assign(expression: c, value: 3)
88 |
89 | var result = expression.evaluate(context)
90 |
--------------------------------------------------------------------------------
/source-cn/behavioral/iterator.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍫 迭代器(Iterator)
3 | ---------------
4 |
5 | 迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。
6 |
7 | ### 示例:
8 | */
9 | struct Novella {
10 | let name: String
11 | }
12 |
13 | struct Novellas {
14 | let novellas: [Novella]
15 | }
16 |
17 | struct NovellasIterator: IteratorProtocol {
18 |
19 | private var current = 0
20 | private let novellas: [Novella]
21 |
22 | init(novellas: [Novella]) {
23 | self.novellas = novellas
24 | }
25 |
26 | mutating func next() -> Novella? {
27 | defer { current += 1 }
28 | return novellas.count > current ? novellas[current] : nil
29 | }
30 | }
31 |
32 | extension Novellas: Sequence {
33 | func makeIterator() -> NovellasIterator {
34 | return NovellasIterator(novellas: novellas)
35 | }
36 | }
37 | /*:
38 | ### 用法
39 | */
40 | let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
41 |
42 | for novella in greatNovellas {
43 | print("I've read: \(novella)")
44 | }
45 |
--------------------------------------------------------------------------------
/source-cn/behavioral/mediator.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💐 中介者(Mediator)
3 | ---------------
4 |
5 | 用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互。
6 |
7 | ### 示例:
8 | */
9 | protocol Receiver {
10 | associatedtype MessageType
11 | func receive(message: MessageType)
12 | }
13 |
14 | protocol Sender {
15 | associatedtype MessageType
16 | associatedtype ReceiverType: Receiver
17 |
18 | var recipients: [ReceiverType] { get }
19 |
20 | func send(message: MessageType)
21 | }
22 |
23 | struct Programmer: Receiver {
24 | let name: String
25 |
26 | init(name: String) {
27 | self.name = name
28 | }
29 |
30 | func receive(message: String) {
31 | print("\(name) received: \(message)")
32 | }
33 | }
34 |
35 | final class MessageMediator: Sender {
36 | internal var recipients: [Programmer] = []
37 |
38 | func add(recipient: Programmer) {
39 | recipients.append(recipient)
40 | }
41 |
42 | func send(message: String) {
43 | for recipient in recipients {
44 | recipient.receive(message: message)
45 | }
46 | }
47 | }
48 |
49 | /*:
50 | ### 用法
51 | */
52 | func spamMonster(message: String, worker: MessageMediator) {
53 | worker.send(message: message)
54 | }
55 |
56 | let messagesMediator = MessageMediator()
57 |
58 | let user0 = Programmer(name: "Linus Torvalds")
59 | let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
60 | messagesMediator.add(recipient: user0)
61 | messagesMediator.add(recipient: user1)
62 |
63 | spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
64 |
65 |
--------------------------------------------------------------------------------
/source-cn/behavioral/memento.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💾 备忘录(Memento)
3 | --------------
4 |
5 | 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
6 |
7 | ### 示例:
8 | */
9 | typealias Memento = [String: String]
10 | /*:
11 | 发起人(Originator)
12 | */
13 | protocol MementoConvertible {
14 | var memento: Memento { get }
15 | init?(memento: Memento)
16 | }
17 |
18 | struct GameState: MementoConvertible {
19 |
20 | private enum Keys {
21 | static let chapter = "com.valve.halflife.chapter"
22 | static let weapon = "com.valve.halflife.weapon"
23 | }
24 |
25 | var chapter: String
26 | var weapon: String
27 |
28 | init(chapter: String, weapon: String) {
29 | self.chapter = chapter
30 | self.weapon = weapon
31 | }
32 |
33 | init?(memento: Memento) {
34 | guard let mementoChapter = memento[Keys.chapter],
35 | let mementoWeapon = memento[Keys.weapon] else {
36 | return nil
37 | }
38 |
39 | chapter = mementoChapter
40 | weapon = mementoWeapon
41 | }
42 |
43 | var memento: Memento {
44 | return [ Keys.chapter: chapter, Keys.weapon: weapon ]
45 | }
46 | }
47 | /*:
48 | 管理者(Caretaker)
49 | */
50 | enum CheckPoint {
51 |
52 | private static let defaults = UserDefaults.standard
53 |
54 | static func save(_ state: MementoConvertible, saveName: String) {
55 | defaults.set(state.memento, forKey: saveName)
56 | defaults.synchronize()
57 | }
58 |
59 | static func restore(saveName: String) -> Any? {
60 | return defaults.object(forKey: saveName)
61 | }
62 | }
63 | /*:
64 | ### 用法
65 | */
66 | var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
67 |
68 | gameState.chapter = "Anomalous Materials"
69 | gameState.weapon = "Glock 17"
70 | CheckPoint.save(gameState, saveName: "gameState1")
71 |
72 | gameState.chapter = "Unforeseen Consequences"
73 | gameState.weapon = "MP5"
74 | CheckPoint.save(gameState, saveName: "gameState2")
75 |
76 | gameState.chapter = "Office Complex"
77 | gameState.weapon = "Crossbow"
78 | CheckPoint.save(gameState, saveName: "gameState3")
79 |
80 | if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
81 | let finalState = GameState(memento: memento)
82 | dump(finalState)
83 | }
84 |
--------------------------------------------------------------------------------
/source-cn/behavioral/observer.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 👓 观察者(Observer)
3 | ---------------
4 |
5 | 一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知
6 |
7 | ### 示例:
8 | */
9 | protocol PropertyObserver : class {
10 | func willChange(propertyName: String, newPropertyValue: Any?)
11 | func didChange(propertyName: String, oldPropertyValue: Any?)
12 | }
13 |
14 | final class TestChambers {
15 |
16 | weak var observer:PropertyObserver?
17 |
18 | private let testChamberNumberName = "testChamberNumber"
19 |
20 | var testChamberNumber: Int = 0 {
21 | willSet(newValue) {
22 | observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
23 | }
24 | didSet {
25 | observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
26 | }
27 | }
28 | }
29 |
30 | final class Observer : PropertyObserver {
31 | func willChange(propertyName: String, newPropertyValue: Any?) {
32 | if newPropertyValue as? Int == 1 {
33 | print("Okay. Look. We both said a lot of things that you're going to regret.")
34 | }
35 | }
36 |
37 | func didChange(propertyName: String, oldPropertyValue: Any?) {
38 | if oldPropertyValue as? Int == 0 {
39 | print("Sorry about the mess. I've really let the place go since you killed me.")
40 | }
41 | }
42 | }
43 | /*:
44 | ### 用法
45 | */
46 | var observerInstance = Observer()
47 | var testChambers = TestChambers()
48 | testChambers.observer = observerInstance
49 | testChambers.testChamberNumber += 1
50 |
--------------------------------------------------------------------------------
/source-cn/behavioral/state.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🐉 状态(State)
3 | ---------
4 |
5 | 在状态模式中,对象的行为是基于它的内部状态而改变的。
6 | 这个模式允许某个类对象在运行时发生改变。
7 |
8 | ### 示例:
9 | */
10 | final class Context {
11 | private var state: State = UnauthorizedState()
12 |
13 | var isAuthorized: Bool {
14 | get { return state.isAuthorized(context: self) }
15 | }
16 |
17 | var userId: String? {
18 | get { return state.userId(context: self) }
19 | }
20 |
21 | func changeStateToAuthorized(userId: String) {
22 | state = AuthorizedState(userId: userId)
23 | }
24 |
25 | func changeStateToUnauthorized() {
26 | state = UnauthorizedState()
27 | }
28 | }
29 |
30 | protocol State {
31 | func isAuthorized(context: Context) -> Bool
32 | func userId(context: Context) -> String?
33 | }
34 |
35 | class UnauthorizedState: State {
36 | func isAuthorized(context: Context) -> Bool { return false }
37 |
38 | func userId(context: Context) -> String? { return nil }
39 | }
40 |
41 | class AuthorizedState: State {
42 | let userId: String
43 |
44 | init(userId: String) { self.userId = userId }
45 |
46 | func isAuthorized(context: Context) -> Bool { return true }
47 |
48 | func userId(context: Context) -> String? { return userId }
49 | }
50 | /*:
51 | ### 用法
52 | */
53 | let userContext = Context()
54 | (userContext.isAuthorized, userContext.userId)
55 | userContext.changeStateToAuthorized(userId: "admin")
56 | (userContext.isAuthorized, userContext.userId) // now logged in as "admin"
57 | userContext.changeStateToUnauthorized()
58 | (userContext.isAuthorized, userContext.userId)
59 |
--------------------------------------------------------------------------------
/source-cn/behavioral/strategy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💡 策略(Strategy)
3 | --------------
4 |
5 | 对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:
6 | * 定义了一族算法(业务规则);
7 | * 封装了每个算法;
8 | * 这族的算法可互换代替(interchangeable)。
9 |
10 | ### 示例:
11 | */
12 |
13 | struct TestSubject {
14 | let pupilDiameter: Double
15 | let blushResponse: Double
16 | let isOrganic: Bool
17 | }
18 |
19 | protocol RealnessTesting: AnyObject {
20 | func testRealness(_ testSubject: TestSubject) -> Bool
21 | }
22 |
23 | final class VoightKampffTest: RealnessTesting {
24 | func testRealness(_ testSubject: TestSubject) -> Bool {
25 | return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
26 | }
27 | }
28 |
29 | final class GeneticTest: RealnessTesting {
30 | func testRealness(_ testSubject: TestSubject) -> Bool {
31 | return testSubject.isOrganic
32 | }
33 | }
34 |
35 | final class BladeRunner {
36 | private let strategy: RealnessTesting
37 |
38 | init(test: RealnessTesting) {
39 | self.strategy = test
40 | }
41 |
42 | func testIfAndroid(_ testSubject: TestSubject) -> Bool {
43 | return !strategy.testRealness(testSubject)
44 | }
45 | }
46 |
47 | /*:
48 | ### 用法
49 | */
50 |
51 | let rachel = TestSubject(pupilDiameter: 30.2,
52 | blushResponse: 0.3,
53 | isOrganic: false)
54 |
55 | // Deckard is using a traditional test
56 | let deckard = BladeRunner(test: VoightKampffTest())
57 | let isRachelAndroid = deckard.testIfAndroid(rachel)
58 |
59 | // Gaff is using a very precise method
60 | let gaff = BladeRunner(test: GeneticTest())
61 | let isDeckardAndroid = gaff.testIfAndroid(rachel)
62 |
--------------------------------------------------------------------------------
/source-cn/behavioral/template_method.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 📝 模板方法模式
3 | -----------
4 |
5 | 模板方法模式是一种行为设计模式, 它通过父类/协议中定义了一个算法的框架, 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。
6 |
7 | ### 示例:
8 | */
9 | protocol Garden {
10 | func prepareSoil()
11 | func plantSeeds()
12 | func waterPlants()
13 | func prepareGarden()
14 | }
15 |
16 | extension Garden {
17 |
18 | func prepareGarden() {
19 | prepareSoil()
20 | plantSeeds()
21 | waterPlants()
22 | }
23 | }
24 |
25 | final class RoseGarden: Garden {
26 |
27 | func prepare() {
28 | prepareGarden()
29 | }
30 |
31 | func prepareSoil() {
32 | print ("prepare soil for rose garden")
33 | }
34 |
35 | func plantSeeds() {
36 | print ("plant seeds for rose garden")
37 | }
38 |
39 | func waterPlants() {
40 | print ("water the rose garden")
41 | }
42 | }
43 |
44 | /*:
45 | ### 用法
46 | */
47 |
48 | let roseGarden = RoseGarden()
49 | roseGarden.prepare()
50 |
--------------------------------------------------------------------------------
/source-cn/behavioral/visitor.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🏃 访问者(Visitor)
3 | --------------
4 |
5 | 封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
6 |
7 | ### 示例:
8 | */
9 | protocol PlanetVisitor {
10 | func visit(planet: PlanetAlderaan)
11 | func visit(planet: PlanetCoruscant)
12 | func visit(planet: PlanetTatooine)
13 | func visit(planet: MoonJedha)
14 | }
15 |
16 | protocol Planet {
17 | func accept(visitor: PlanetVisitor)
18 | }
19 |
20 | final class MoonJedha: Planet {
21 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
22 | }
23 |
24 | final class PlanetAlderaan: Planet {
25 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
26 | }
27 |
28 | final class PlanetCoruscant: Planet {
29 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
30 | }
31 |
32 | final class PlanetTatooine: Planet {
33 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
34 | }
35 |
36 | final class NameVisitor: PlanetVisitor {
37 | var name = ""
38 |
39 | func visit(planet: PlanetAlderaan) { name = "Alderaan" }
40 | func visit(planet: PlanetCoruscant) { name = "Coruscant" }
41 | func visit(planet: PlanetTatooine) { name = "Tatooine" }
42 | func visit(planet: MoonJedha) { name = "Jedha" }
43 | }
44 |
45 | /*:
46 | ### 用法
47 | */
48 | let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
49 |
50 | let names = planets.map { (planet: Planet) -> String in
51 | let visitor = NameVisitor()
52 | planet.accept(visitor: visitor)
53 |
54 | return visitor.name
55 | }
56 |
57 | names
58 |
--------------------------------------------------------------------------------
/source-cn/contents.md:
--------------------------------------------------------------------------------
1 |
2 | ## 目录
3 |
4 | * [行为型模式](Behavioral)
5 | * [创建型模式](Creational)
6 | * [结构型模式](Structural)
--------------------------------------------------------------------------------
/source-cn/contentsReadme.md:
--------------------------------------------------------------------------------
1 |
2 | ## 目录
3 |
4 | | [行为型模式](#行为型模式) | [创建型模式](#创建型模式) | [结构型模式](#结构型模式structural) |
5 | | ------------------------------------------------------------ | --------------------------------------------------------- | ------------------------------------------------------------ |
6 | | [🐝 责任链 Chain Of Responsibility](#-责任链chain-of-responsibility) | [🌰 抽象工厂 Abstract Factory](#-抽象工厂abstract-factory) | [🔌 适配器 Adapter](#-适配器adapter) |
7 | | [👫 命令 Command](#-命令command) | [👷 生成器 Builder](#-生成器builder) | [🌉 桥接 Bridge](#-桥接bridge) |
8 | | [🎶 解释器 Interpreter](#-解释器interpreter) | [🏭 工厂方法 Factory Method](#-工厂方法factory-method) | [🌿 组合 Composite](#-组合composite) |
9 | | [🍫 迭代器 Iterator](#-迭代器iterator) | [🔂 单态 Monostate](#-单态monostate) | [🍧 修饰 Decorator](#-修饰decorator) |
10 | | [💐 中介者 Mediator](#-中介者mediator) | [🃏 原型 Prototype](#-原型prototype) | [🎁 外观 Façade](#-外观facade) |
11 | | [💾 备忘录 Memento](#-备忘录memento) | [💍 单例 Singleton](#-单例singleton) | [🍃 享元 Flyweight](#-享元flyweight) |
12 | | [👓 观察者 Observer](#-观察者observer) | | [☔ 保护代理 Protection Proxy](#-保护代理模式protection-proxy) |
13 | | [🐉 状态 State](#-状态state) | | [🍬 虚拟代理 Virtual Proxy](#-虚拟代理virtual-proxy) |
14 | | [💡 策略 Strategy](#-策略strategy) | | |
15 | | [🏃 访问者 Visitor](#-访问者visitor) | | |
16 | | [📝 模板方法 Templdate Method](#-template-method) | | |
17 |
18 |
--------------------------------------------------------------------------------
/source-cn/creational/abstract_factory.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🌰 抽象工厂(Abstract Factory)
3 | -------------
4 |
5 | 抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。
6 |
7 | ### 示例:
8 |
9 | 协议
10 | */
11 |
12 | protocol BurgerDescribing {
13 | var ingredients: [String] { get }
14 | }
15 |
16 | struct CheeseBurger: BurgerDescribing {
17 | let ingredients: [String]
18 | }
19 |
20 | protocol BurgerMaking {
21 | func make() -> BurgerDescribing
22 | }
23 |
24 | // 工厂方法实现
25 |
26 | final class BigKahunaBurger: BurgerMaking {
27 | func make() -> BurgerDescribing {
28 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
29 | }
30 | }
31 |
32 | final class JackInTheBox: BurgerMaking {
33 | func make() -> BurgerDescribing {
34 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
35 | }
36 | }
37 |
38 | /*:
39 | 抽象工厂
40 | */
41 |
42 | enum BurgerFactoryType: BurgerMaking {
43 |
44 | case bigKahuna
45 | case jackInTheBox
46 |
47 | func make() -> BurgerDescribing {
48 | switch self {
49 | case .bigKahuna:
50 | return BigKahunaBurger().make()
51 | case .jackInTheBox:
52 | return JackInTheBox().make()
53 | }
54 | }
55 | }
56 | /*:
57 | ### 用法
58 | */
59 | let bigKahuna = BurgerFactoryType.bigKahuna.make()
60 | let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
61 |
--------------------------------------------------------------------------------
/source-cn/creational/builder.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 👷 生成器(Builder)
3 | --------------
4 |
5 | 一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。
6 |
7 | ### 示例:
8 | */
9 | final class DeathStarBuilder {
10 |
11 | var x: Double?
12 | var y: Double?
13 | var z: Double?
14 |
15 | typealias BuilderClosure = (DeathStarBuilder) -> ()
16 |
17 | init(buildClosure: BuilderClosure) {
18 | buildClosure(self)
19 | }
20 | }
21 |
22 | struct DeathStar : CustomStringConvertible {
23 |
24 | let x: Double
25 | let y: Double
26 | let z: Double
27 |
28 | init?(builder: DeathStarBuilder) {
29 |
30 | if let x = builder.x, let y = builder.y, let z = builder.z {
31 | self.x = x
32 | self.y = y
33 | self.z = z
34 | } else {
35 | return nil
36 | }
37 | }
38 |
39 | var description:String {
40 | return "Death Star at (x:\(x) y:\(y) z:\(z))"
41 | }
42 | }
43 | /*:
44 | ### 用法
45 | */
46 | let empire = DeathStarBuilder { builder in
47 | builder.x = 0.1
48 | builder.y = 0.2
49 | builder.z = 0.3
50 | }
51 |
52 | let deathStar = DeathStar(builder:empire)
53 |
--------------------------------------------------------------------------------
/source-cn/creational/factory.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🏭 工厂方法(Factory Method)
3 | -----------------------
4 |
5 | 定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
6 |
7 | ### 示例:
8 | */
9 | protocol CurrencyDescribing {
10 | var symbol: String { get }
11 | var code: String { get }
12 | }
13 |
14 | final class Euro: CurrencyDescribing {
15 | var symbol: String {
16 | return "€"
17 | }
18 |
19 | var code: String {
20 | return "EUR"
21 | }
22 | }
23 |
24 | final class UnitedStatesDolar: CurrencyDescribing {
25 | var symbol: String {
26 | return "$"
27 | }
28 |
29 | var code: String {
30 | return "USD"
31 | }
32 | }
33 |
34 | enum Country {
35 | case unitedStates
36 | case spain
37 | case uk
38 | case greece
39 | }
40 |
41 | enum CurrencyFactory {
42 | static func currency(for country: Country) -> CurrencyDescribing? {
43 |
44 | switch country {
45 | case .spain, .greece:
46 | return Euro()
47 | case .unitedStates:
48 | return UnitedStatesDolar()
49 | default:
50 | return nil
51 | }
52 |
53 | }
54 | }
55 | /*:
56 | ### 用法
57 | */
58 | let noCurrencyCode = "No Currency Code Available"
59 |
60 | CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
61 | CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
62 | CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
63 | CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
64 |
--------------------------------------------------------------------------------
/source-cn/creational/header.md:
--------------------------------------------------------------------------------
1 |
2 | 创建型模式
3 | ========
4 |
5 | > 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。
6 | >
7 | >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
8 |
--------------------------------------------------------------------------------
/source-cn/creational/monostate.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🔂 单态(Monostate)
3 | ------------
4 |
5 | 单态模式是实现单一共享的另一种方法。不同于单例模式,它通过完全不同的机制,在不限制构造方法的情况下实现单一共享特性。
6 | 因此,在这种情况下,单态会将状态保存为静态,而不是将整个实例保存为单例。
7 | [单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
8 |
9 | ### 示例:
10 | */
11 | class Settings {
12 |
13 | enum Theme {
14 | case `default`
15 | case old
16 | case new
17 | }
18 |
19 | private static var theme: Theme?
20 |
21 | var currentTheme: Theme {
22 | get { Settings.theme ?? .default }
23 | set(newTheme) { Settings.theme = newTheme }
24 | }
25 | }
26 | /*:
27 | ### 用法:
28 | */
29 | import SwiftUI
30 |
31 | // 改变主题
32 | let settings = Settings() // 开始使用主题 .old
33 | settings.currentTheme = .new // 改变主题为 .new
34 |
35 | // 界面一
36 | let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
37 |
38 | // 界面二
39 | let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
40 |
--------------------------------------------------------------------------------
/source-cn/creational/prototype.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🃏 原型(Prototype)
3 | --------------
4 |
5 | 通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。
6 |
7 | ### 示例:
8 | */
9 | class MoonWorker {
10 |
11 | let name: String
12 | var health: Int = 100
13 |
14 | init(name: String) {
15 | self.name = name
16 | }
17 |
18 | func clone() -> MoonWorker {
19 | return MoonWorker(name: name)
20 | }
21 | }
22 | /*:
23 | ### 用法
24 | */
25 | let prototype = MoonWorker(name: "Sam Bell")
26 |
27 | var bell1 = prototype.clone()
28 | bell1.health = 12
29 |
30 | var bell2 = prototype.clone()
31 | bell2.health = 23
32 |
33 | var bell3 = prototype.clone()
34 | bell3.health = 0
35 |
--------------------------------------------------------------------------------
/source-cn/creational/singleton.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💍 单例(Singleton)
3 | --------------
4 |
5 | 单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为
6 |
7 | ### 示例:
8 | */
9 | final class ElonMusk {
10 |
11 | static let shared = ElonMusk()
12 |
13 | private init() {
14 | // Private initialization to ensure just one instance is created.
15 | }
16 | }
17 | /*:
18 | ### 用法
19 | */
20 | let elon = ElonMusk.shared // There is only one Elon Musk folks.
21 |
--------------------------------------------------------------------------------
/source-cn/endComment:
--------------------------------------------------------------------------------
1 |
2 | */
--------------------------------------------------------------------------------
/source-cn/endSwiftCode:
--------------------------------------------------------------------------------
1 | ```
2 |
3 |
--------------------------------------------------------------------------------
/source-cn/footer.md:
--------------------------------------------------------------------------------
1 |
2 | Info
3 | ====
4 |
5 | 📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)
6 |
--------------------------------------------------------------------------------
/source-cn/imports.swift:
--------------------------------------------------------------------------------
1 |
2 | import Foundation
3 |
--------------------------------------------------------------------------------
/source-cn/startComment:
--------------------------------------------------------------------------------
1 | /*:
2 |
--------------------------------------------------------------------------------
/source-cn/startSwiftCode:
--------------------------------------------------------------------------------
1 |
2 |
3 | ```swift
--------------------------------------------------------------------------------
/source-cn/structural/adapter.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🔌 适配器(Adapter)
3 | --------------
4 |
5 | 适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
6 |
7 | ### 示例:
8 | */
9 | protocol NewDeathStarSuperLaserAiming {
10 | var angleV: Double { get }
11 | var angleH: Double { get }
12 | }
13 | /*:
14 | **被适配者**
15 | */
16 | struct OldDeathStarSuperlaserTarget {
17 | let angleHorizontal: Float
18 | let angleVertical: Float
19 |
20 | init(angleHorizontal: Float, angleVertical: Float) {
21 | self.angleHorizontal = angleHorizontal
22 | self.angleVertical = angleVertical
23 | }
24 | }
25 | /*:
26 | **适配器**
27 | */
28 | struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
29 |
30 | private let target: OldDeathStarSuperlaserTarget
31 |
32 | var angleV: Double {
33 | return Double(target.angleVertical)
34 | }
35 |
36 | var angleH: Double {
37 | return Double(target.angleHorizontal)
38 | }
39 |
40 | init(_ target: OldDeathStarSuperlaserTarget) {
41 | self.target = target
42 | }
43 | }
44 | /*:
45 | ### 用法
46 | */
47 | let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
48 | let newFormat = NewDeathStarSuperlaserTarget(target)
49 |
50 | newFormat.angleH
51 | newFormat.angleV
52 |
--------------------------------------------------------------------------------
/source-cn/structural/bridge.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🌉 桥接(Bridge)
3 | -----------
4 |
5 | 桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。
6 |
7 | ### 示例:
8 | */
9 | protocol Switch {
10 | var appliance: Appliance { get set }
11 | func turnOn()
12 | }
13 |
14 | protocol Appliance {
15 | func run()
16 | }
17 |
18 | final class RemoteControl: Switch {
19 | var appliance: Appliance
20 |
21 | func turnOn() {
22 | self.appliance.run()
23 | }
24 |
25 | init(appliance: Appliance) {
26 | self.appliance = appliance
27 | }
28 | }
29 |
30 | final class TV: Appliance {
31 | func run() {
32 | print("tv turned on");
33 | }
34 | }
35 |
36 | final class VacuumCleaner: Appliance {
37 | func run() {
38 | print("vacuum cleaner turned on")
39 | }
40 | }
41 | /*:
42 | ### 用法
43 | */
44 | let tvRemoteControl = RemoteControl(appliance: TV())
45 | tvRemoteControl.turnOn()
46 |
47 | let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
48 | fancyVacuumCleanerRemoteControl.turnOn()
49 |
--------------------------------------------------------------------------------
/source-cn/structural/composite.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🌿 组合(Composite)
3 | --------------
4 |
5 | 将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
6 |
7 | ### 示例:
8 |
9 | 组件(Component)
10 | */
11 | protocol Shape {
12 | func draw(fillColor: String)
13 | }
14 | /*:
15 | 叶子节点(Leafs)
16 | */
17 | final class Square: Shape {
18 | func draw(fillColor: String) {
19 | print("Drawing a Square with color \(fillColor)")
20 | }
21 | }
22 |
23 | final class Circle: Shape {
24 | func draw(fillColor: String) {
25 | print("Drawing a circle with color \(fillColor)")
26 | }
27 | }
28 |
29 | /*:
30 | 组合
31 | */
32 | final class Whiteboard: Shape {
33 |
34 | private lazy var shapes = [Shape]()
35 |
36 | init(_ shapes: Shape...) {
37 | self.shapes = shapes
38 | }
39 |
40 | func draw(fillColor: String) {
41 | for shape in self.shapes {
42 | shape.draw(fillColor: fillColor)
43 | }
44 | }
45 | }
46 | /*:
47 | ### 用法
48 | */
49 | var whiteboard = Whiteboard(Circle(), Square())
50 | whiteboard.draw(fillColor: "Red")
51 |
--------------------------------------------------------------------------------
/source-cn/structural/decorator.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍧 修饰(Decorator)
3 | --------------
4 |
5 | 修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。
6 | 就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。
7 |
8 | ### 示例:
9 | */
10 | protocol CostHaving {
11 | var cost: Double { get }
12 | }
13 |
14 | protocol IngredientsHaving {
15 | var ingredients: [String] { get }
16 | }
17 |
18 | typealias BeverageDataHaving = CostHaving & IngredientsHaving
19 |
20 | struct SimpleCoffee: BeverageDataHaving {
21 | let cost: Double = 1.0
22 | let ingredients = ["Water", "Coffee"]
23 | }
24 |
25 | protocol BeverageHaving: BeverageDataHaving {
26 | var beverage: BeverageDataHaving { get }
27 | }
28 |
29 | struct Milk: BeverageHaving {
30 |
31 | let beverage: BeverageDataHaving
32 |
33 | var cost: Double {
34 | return beverage.cost + 0.5
35 | }
36 |
37 | var ingredients: [String] {
38 | return beverage.ingredients + ["Milk"]
39 | }
40 | }
41 |
42 | struct WhipCoffee: BeverageHaving {
43 |
44 | let beverage: BeverageDataHaving
45 |
46 | var cost: Double {
47 | return beverage.cost + 0.5
48 | }
49 |
50 | var ingredients: [String] {
51 | return beverage.ingredients + ["Whip"]
52 | }
53 | }
54 | /*:
55 | ### 用法
56 | */
57 | var someCoffee: BeverageDataHaving = SimpleCoffee()
58 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
59 | someCoffee = Milk(beverage: someCoffee)
60 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
61 | someCoffee = WhipCoffee(beverage: someCoffee)
62 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
63 |
--------------------------------------------------------------------------------
/source-cn/structural/facade.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🎁 外观(Facade)
3 | -----------
4 |
5 | 外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。
6 |
7 | ### 示例:
8 | */
9 | final class Defaults {
10 |
11 | private let defaults: UserDefaults
12 |
13 | init(defaults: UserDefaults = .standard) {
14 | self.defaults = defaults
15 | }
16 |
17 | subscript(key: String) -> String? {
18 | get {
19 | return defaults.string(forKey: key)
20 | }
21 |
22 | set {
23 | defaults.set(newValue, forKey: key)
24 | }
25 | }
26 | }
27 | /*:
28 | ### 用法
29 | */
30 | let storage = Defaults()
31 |
32 | // Store
33 | storage["Bishop"] = "Disconnect me. I’d rather be nothing"
34 |
35 | // Read
36 | storage["Bishop"]
37 |
--------------------------------------------------------------------------------
/source-cn/structural/flyweight.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍃 享元(Flyweight)
3 | --------------
4 |
5 | 使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。
6 |
7 | ### 示例:
8 | */
9 | // 特指咖啡生成的对象会是享元
10 | struct SpecialityCoffee {
11 | let origin: String
12 | }
13 |
14 | protocol CoffeeSearching {
15 | func search(origin: String) -> SpecialityCoffee?
16 | }
17 |
18 | // 菜单充当特制咖啡享元对象的工厂和缓存
19 | final class Menu: CoffeeSearching {
20 |
21 | private var coffeeAvailable: [String: SpecialityCoffee] = [:]
22 |
23 | func search(origin: String) -> SpecialityCoffee? {
24 | if coffeeAvailable.index(forKey: origin) == nil {
25 | coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
26 | }
27 |
28 | return coffeeAvailable[origin]
29 | }
30 | }
31 |
32 | final class CoffeeShop {
33 | private var orders: [Int: SpecialityCoffee] = [:]
34 | private let menu: CoffeeSearching
35 |
36 | init(menu: CoffeeSearching) {
37 | self.menu = menu
38 | }
39 |
40 | func takeOrder(origin: String, table: Int) {
41 | orders[table] = menu.search(origin: origin)
42 | }
43 |
44 | func serve() {
45 | for (table, origin) in orders {
46 | print("Serving \(origin) to table \(table)")
47 | }
48 | }
49 | }
50 | /*:
51 | ### 用法
52 | */
53 | let coffeeShop = CoffeeShop(menu: Menu())
54 |
55 | coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
56 | coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
57 |
58 | coffeeShop.serve()
59 |
--------------------------------------------------------------------------------
/source-cn/structural/header.md:
--------------------------------------------------------------------------------
1 |
2 | 结构型模式(Structural)
3 | ====================
4 |
5 | > 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。
6 | >
7 | >**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)
8 |
--------------------------------------------------------------------------------
/source-cn/structural/protection_proxy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | ☔ 保护代理模式(Protection Proxy)
3 | ------------------
4 |
5 | 在代理模式中,创建一个类代表另一个底层类的功能。
6 | 保护代理用于限制访问。
7 |
8 | ### 示例:
9 | */
10 | protocol DoorOpening {
11 | func open(doors: String) -> String
12 | }
13 |
14 | final class HAL9000: DoorOpening {
15 | func open(doors: String) -> String {
16 | return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
17 | }
18 | }
19 |
20 | final class CurrentComputer: DoorOpening {
21 | private var computer: HAL9000!
22 |
23 | func authenticate(password: String) -> Bool {
24 |
25 | guard password == "pass" else {
26 | return false
27 | }
28 |
29 | computer = HAL9000()
30 |
31 | return true
32 | }
33 |
34 | func open(doors: String) -> String {
35 |
36 | guard computer != nil else {
37 | return "Access Denied. I'm afraid I can't do that."
38 | }
39 |
40 | return computer.open(doors: doors)
41 | }
42 | }
43 | /*:
44 | ### 用法
45 | */
46 | let computer = CurrentComputer()
47 | let podBay = "Pod Bay Doors"
48 |
49 | computer.open(doors: podBay)
50 |
51 | computer.authenticate(password: "pass")
52 | computer.open(doors: podBay)
53 |
--------------------------------------------------------------------------------
/source-cn/structural/virtual_proxy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍬 虚拟代理(Virtual Proxy)
3 | ----------------
4 |
5 | 在代理模式中,创建一个类代表另一个底层类的功能。
6 | 虚拟代理用于对象的需时加载。
7 |
8 | ### 示例:
9 | */
10 | protocol HEVSuitMedicalAid {
11 | func administerMorphine() -> String
12 | }
13 |
14 | final class HEVSuit: HEVSuitMedicalAid {
15 | func administerMorphine() -> String {
16 | return "Morphine administered."
17 | }
18 | }
19 |
20 | final class HEVSuitHumanInterface: HEVSuitMedicalAid {
21 |
22 | lazy private var physicalSuit: HEVSuit = HEVSuit()
23 |
24 | func administerMorphine() -> String {
25 | return physicalSuit.administerMorphine()
26 | }
27 | }
28 | /*:
29 | ### 用法
30 | */
31 | let humanInterface = HEVSuitHumanInterface()
32 | humanInterface.administerMorphine()
33 |
--------------------------------------------------------------------------------
/source/Index/header.md:
--------------------------------------------------------------------------------
1 |
2 | Design Patterns implemented in Swift 5.0
3 | ========================================
4 |
5 | A short cheat-sheet with Xcode 10.2 Playground ([Design-Patterns.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns.playground.zip)).
6 |
7 | ### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)
8 |
9 | 👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)
10 |
11 | 👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。
12 |
13 | 🚀 How to generate README, Playground and zip from source: [GENERATE.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/GENERATE.md)
14 |
--------------------------------------------------------------------------------
/source/Index/welcome.swift:
--------------------------------------------------------------------------------
1 |
2 | print("Welcome!")
3 |
--------------------------------------------------------------------------------
/source/behavioral/chain_of_responsibility.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🐝 Chain Of Responsibility
3 | --------------------------
4 |
5 | The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
6 |
7 | ### Example:
8 | */
9 |
10 | protocol Withdrawing {
11 | func withdraw(amount: Int) -> Bool
12 | }
13 |
14 | final class MoneyPile: Withdrawing {
15 |
16 | let value: Int
17 | var quantity: Int
18 | var next: Withdrawing?
19 |
20 | init(value: Int, quantity: Int, next: Withdrawing?) {
21 | self.value = value
22 | self.quantity = quantity
23 | self.next = next
24 | }
25 |
26 | func withdraw(amount: Int) -> Bool {
27 |
28 | var amount = amount
29 |
30 | func canTakeSomeBill(want: Int) -> Bool {
31 | return (want / self.value) > 0
32 | }
33 |
34 | var quantity = self.quantity
35 |
36 | while canTakeSomeBill(want: amount) {
37 |
38 | if quantity == 0 {
39 | break
40 | }
41 |
42 | amount -= self.value
43 | quantity -= 1
44 | }
45 |
46 | guard amount > 0 else {
47 | return true
48 | }
49 |
50 | if let next = self.next {
51 | return next.withdraw(amount: amount)
52 | }
53 |
54 | return false
55 | }
56 | }
57 |
58 | final class ATM: Withdrawing {
59 |
60 | private var hundred: Withdrawing
61 | private var fifty: Withdrawing
62 | private var twenty: Withdrawing
63 | private var ten: Withdrawing
64 |
65 | private var startPile: Withdrawing {
66 | return self.hundred
67 | }
68 |
69 | init(hundred: Withdrawing,
70 | fifty: Withdrawing,
71 | twenty: Withdrawing,
72 | ten: Withdrawing) {
73 |
74 | self.hundred = hundred
75 | self.fifty = fifty
76 | self.twenty = twenty
77 | self.ten = ten
78 | }
79 |
80 | func withdraw(amount: Int) -> Bool {
81 | return startPile.withdraw(amount: amount)
82 | }
83 | }
84 | /*:
85 | ### Usage
86 | */
87 | // Create piles of money and link them together 10 < 20 < 50 < 100.**
88 | let ten = MoneyPile(value: 10, quantity: 6, next: nil)
89 | let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
90 | let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
91 | let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
92 |
93 | // Build ATM.
94 | var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
95 | atm.withdraw(amount: 310) // Cannot because ATM has only 300
96 | atm.withdraw(amount: 100) // Can withdraw - 1x100
97 |
--------------------------------------------------------------------------------
/source/behavioral/command.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 👫 Command
3 | ----------
4 |
5 | The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
6 |
7 | ### Example:
8 | */
9 | protocol DoorCommand {
10 | func execute() -> String
11 | }
12 |
13 | final class OpenCommand: DoorCommand {
14 | let doors:String
15 |
16 | required init(doors: String) {
17 | self.doors = doors
18 | }
19 |
20 | func execute() -> String {
21 | return "Opened \(doors)"
22 | }
23 | }
24 |
25 | final class CloseCommand: DoorCommand {
26 | let doors:String
27 |
28 | required init(doors: String) {
29 | self.doors = doors
30 | }
31 |
32 | func execute() -> String {
33 | return "Closed \(doors)"
34 | }
35 | }
36 |
37 | final class HAL9000DoorsOperations {
38 | let openCommand: DoorCommand
39 | let closeCommand: DoorCommand
40 |
41 | init(doors: String) {
42 | self.openCommand = OpenCommand(doors:doors)
43 | self.closeCommand = CloseCommand(doors:doors)
44 | }
45 |
46 | func close() -> String {
47 | return closeCommand.execute()
48 | }
49 |
50 | func open() -> String {
51 | return openCommand.execute()
52 | }
53 | }
54 | /*:
55 | ### Usage:
56 | */
57 | let podBayDoors = "Pod Bay Doors"
58 | let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
59 |
60 | doorModule.open()
61 | doorModule.close()
62 |
--------------------------------------------------------------------------------
/source/behavioral/header.md:
--------------------------------------------------------------------------------
1 |
2 | Behavioral
3 | ==========
4 |
5 | >In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
6 | >
7 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
8 |
--------------------------------------------------------------------------------
/source/behavioral/interpreter.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🎶 Interpreter
3 | --------------
4 |
5 | The interpreter pattern is used to evaluate sentences in a language.
6 |
7 | ### Example
8 | */
9 |
10 | protocol IntegerExpression {
11 | func evaluate(_ context: IntegerContext) -> Int
12 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
13 | func copied() -> IntegerExpression
14 | }
15 |
16 | final class IntegerContext {
17 | private var data: [Character:Int] = [:]
18 |
19 | func lookup(name: Character) -> Int {
20 | return self.data[name]!
21 | }
22 |
23 | func assign(expression: IntegerVariableExpression, value: Int) {
24 | self.data[expression.name] = value
25 | }
26 | }
27 |
28 | final class IntegerVariableExpression: IntegerExpression {
29 | let name: Character
30 |
31 | init(name: Character) {
32 | self.name = name
33 | }
34 |
35 | func evaluate(_ context: IntegerContext) -> Int {
36 | return context.lookup(name: self.name)
37 | }
38 |
39 | func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
40 | if name == self.name {
41 | return integerExpression.copied()
42 | } else {
43 | return IntegerVariableExpression(name: self.name)
44 | }
45 | }
46 |
47 | func copied() -> IntegerExpression {
48 | return IntegerVariableExpression(name: self.name)
49 | }
50 | }
51 |
52 | final class AddExpression: IntegerExpression {
53 | private var operand1: IntegerExpression
54 | private var operand2: IntegerExpression
55 |
56 | init(op1: IntegerExpression, op2: IntegerExpression) {
57 | self.operand1 = op1
58 | self.operand2 = op2
59 | }
60 |
61 | func evaluate(_ context: IntegerContext) -> Int {
62 | return self.operand1.evaluate(context) + self.operand2.evaluate(context)
63 | }
64 |
65 | func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
66 | return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
67 | op2: operand2.replace(character: character, integerExpression: integerExpression))
68 | }
69 |
70 | func copied() -> IntegerExpression {
71 | return AddExpression(op1: self.operand1, op2: self.operand2)
72 | }
73 | }
74 | /*:
75 | ### Usage
76 | */
77 | var context = IntegerContext()
78 |
79 | var a = IntegerVariableExpression(name: "A")
80 | var b = IntegerVariableExpression(name: "B")
81 | var c = IntegerVariableExpression(name: "C")
82 |
83 | var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
84 |
85 | context.assign(expression: a, value: 2)
86 | context.assign(expression: b, value: 1)
87 | context.assign(expression: c, value: 3)
88 |
89 | var result = expression.evaluate(context)
90 |
--------------------------------------------------------------------------------
/source/behavioral/iterator.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍫 Iterator
3 | -----------
4 |
5 | The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
6 |
7 | ### Example:
8 | */
9 | struct Novella {
10 | let name: String
11 | }
12 |
13 | struct Novellas {
14 | let novellas: [Novella]
15 | }
16 |
17 | struct NovellasIterator: IteratorProtocol {
18 |
19 | private var current = 0
20 | private let novellas: [Novella]
21 |
22 | init(novellas: [Novella]) {
23 | self.novellas = novellas
24 | }
25 |
26 | mutating func next() -> Novella? {
27 | defer { current += 1 }
28 | return novellas.count > current ? novellas[current] : nil
29 | }
30 | }
31 |
32 | extension Novellas: Sequence {
33 | func makeIterator() -> NovellasIterator {
34 | return NovellasIterator(novellas: novellas)
35 | }
36 | }
37 | /*:
38 | ### Usage
39 | */
40 | let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
41 |
42 | for novella in greatNovellas {
43 | print("I've read: \(novella)")
44 | }
45 |
--------------------------------------------------------------------------------
/source/behavioral/mediator.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💐 Mediator
3 | -----------
4 |
5 | The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
6 |
7 | ### Example
8 | */
9 | protocol Receiver {
10 | associatedtype MessageType
11 | func receive(message: MessageType)
12 | }
13 |
14 | protocol Sender {
15 | associatedtype MessageType
16 | associatedtype ReceiverType: Receiver
17 |
18 | var recipients: [ReceiverType] { get }
19 |
20 | func send(message: MessageType)
21 | }
22 |
23 | struct Programmer: Receiver {
24 | let name: String
25 |
26 | init(name: String) {
27 | self.name = name
28 | }
29 |
30 | func receive(message: String) {
31 | print("\(name) received: \(message)")
32 | }
33 | }
34 |
35 | final class MessageMediator: Sender {
36 | internal var recipients: [Programmer] = []
37 |
38 | func add(recipient: Programmer) {
39 | recipients.append(recipient)
40 | }
41 |
42 | func send(message: String) {
43 | for recipient in recipients {
44 | recipient.receive(message: message)
45 | }
46 | }
47 | }
48 |
49 | /*:
50 | ### Usage
51 | */
52 | func spamMonster(message: String, worker: MessageMediator) {
53 | worker.send(message: message)
54 | }
55 |
56 | let messagesMediator = MessageMediator()
57 |
58 | let user0 = Programmer(name: "Linus Torvalds")
59 | let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
60 | messagesMediator.add(recipient: user0)
61 | messagesMediator.add(recipient: user1)
62 |
63 | spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
64 |
65 |
--------------------------------------------------------------------------------
/source/behavioral/memento.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💾 Memento
3 | ----------
4 |
5 | The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
6 |
7 | ### Example
8 | */
9 | typealias Memento = [String: String]
10 | /*:
11 | Originator
12 | */
13 | protocol MementoConvertible {
14 | var memento: Memento { get }
15 | init?(memento: Memento)
16 | }
17 |
18 | struct GameState: MementoConvertible {
19 |
20 | private enum Keys {
21 | static let chapter = "com.valve.halflife.chapter"
22 | static let weapon = "com.valve.halflife.weapon"
23 | }
24 |
25 | var chapter: String
26 | var weapon: String
27 |
28 | init(chapter: String, weapon: String) {
29 | self.chapter = chapter
30 | self.weapon = weapon
31 | }
32 |
33 | init?(memento: Memento) {
34 | guard let mementoChapter = memento[Keys.chapter],
35 | let mementoWeapon = memento[Keys.weapon] else {
36 | return nil
37 | }
38 |
39 | chapter = mementoChapter
40 | weapon = mementoWeapon
41 | }
42 |
43 | var memento: Memento {
44 | return [ Keys.chapter: chapter, Keys.weapon: weapon ]
45 | }
46 | }
47 | /*:
48 | Caretaker
49 | */
50 | enum CheckPoint {
51 |
52 | private static let defaults = UserDefaults.standard
53 |
54 | static func save(_ state: MementoConvertible, saveName: String) {
55 | defaults.set(state.memento, forKey: saveName)
56 | defaults.synchronize()
57 | }
58 |
59 | static func restore(saveName: String) -> Any? {
60 | return defaults.object(forKey: saveName)
61 | }
62 | }
63 | /*:
64 | ### Usage
65 | */
66 | var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
67 |
68 | gameState.chapter = "Anomalous Materials"
69 | gameState.weapon = "Glock 17"
70 | CheckPoint.save(gameState, saveName: "gameState1")
71 |
72 | gameState.chapter = "Unforeseen Consequences"
73 | gameState.weapon = "MP5"
74 | CheckPoint.save(gameState, saveName: "gameState2")
75 |
76 | gameState.chapter = "Office Complex"
77 | gameState.weapon = "Crossbow"
78 | CheckPoint.save(gameState, saveName: "gameState3")
79 |
80 | if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
81 | let finalState = GameState(memento: memento)
82 | dump(finalState)
83 | }
84 |
--------------------------------------------------------------------------------
/source/behavioral/observer.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 👓 Observer
3 | -----------
4 |
5 | The observer pattern is used to allow an object to publish changes to its state.
6 | Other objects subscribe to be immediately notified of any changes.
7 |
8 | ### Example
9 | */
10 | protocol PropertyObserver : class {
11 | func willChange(propertyName: String, newPropertyValue: Any?)
12 | func didChange(propertyName: String, oldPropertyValue: Any?)
13 | }
14 |
15 | final class TestChambers {
16 |
17 | weak var observer:PropertyObserver?
18 |
19 | private let testChamberNumberName = "testChamberNumber"
20 |
21 | var testChamberNumber: Int = 0 {
22 | willSet(newValue) {
23 | observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
24 | }
25 | didSet {
26 | observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
27 | }
28 | }
29 | }
30 |
31 | final class Observer : PropertyObserver {
32 | func willChange(propertyName: String, newPropertyValue: Any?) {
33 | if newPropertyValue as? Int == 1 {
34 | print("Okay. Look. We both said a lot of things that you're going to regret.")
35 | }
36 | }
37 |
38 | func didChange(propertyName: String, oldPropertyValue: Any?) {
39 | if oldPropertyValue as? Int == 0 {
40 | print("Sorry about the mess. I've really let the place go since you killed me.")
41 | }
42 | }
43 | }
44 | /*:
45 | ### Usage
46 | */
47 | var observerInstance = Observer()
48 | var testChambers = TestChambers()
49 | testChambers.observer = observerInstance
50 | testChambers.testChamberNumber += 1
51 |
--------------------------------------------------------------------------------
/source/behavioral/state.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🐉 State
3 | ---------
4 |
5 | The state pattern is used to alter the behaviour of an object as its internal state changes.
6 | The pattern allows the class for an object to apparently change at run-time.
7 |
8 | ### Example
9 | */
10 | final class Context {
11 | private var state: State = UnauthorizedState()
12 |
13 | var isAuthorized: Bool {
14 | get { return state.isAuthorized(context: self) }
15 | }
16 |
17 | var userId: String? {
18 | get { return state.userId(context: self) }
19 | }
20 |
21 | func changeStateToAuthorized(userId: String) {
22 | state = AuthorizedState(userId: userId)
23 | }
24 |
25 | func changeStateToUnauthorized() {
26 | state = UnauthorizedState()
27 | }
28 | }
29 |
30 | protocol State {
31 | func isAuthorized(context: Context) -> Bool
32 | func userId(context: Context) -> String?
33 | }
34 |
35 | class UnauthorizedState: State {
36 | func isAuthorized(context: Context) -> Bool { return false }
37 |
38 | func userId(context: Context) -> String? { return nil }
39 | }
40 |
41 | class AuthorizedState: State {
42 | let userId: String
43 |
44 | init(userId: String) { self.userId = userId }
45 |
46 | func isAuthorized(context: Context) -> Bool { return true }
47 |
48 | func userId(context: Context) -> String? { return userId }
49 | }
50 | /*:
51 | ### Usage
52 | */
53 | let userContext = Context()
54 | (userContext.isAuthorized, userContext.userId)
55 | userContext.changeStateToAuthorized(userId: "admin")
56 | (userContext.isAuthorized, userContext.userId) // now logged in as "admin"
57 | userContext.changeStateToUnauthorized()
58 | (userContext.isAuthorized, userContext.userId)
59 |
--------------------------------------------------------------------------------
/source/behavioral/strategy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💡 Strategy
3 | -----------
4 |
5 | The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
6 |
7 | ### Example
8 | */
9 |
10 | struct TestSubject {
11 | let pupilDiameter: Double
12 | let blushResponse: Double
13 | let isOrganic: Bool
14 | }
15 |
16 | protocol RealnessTesting: AnyObject {
17 | func testRealness(_ testSubject: TestSubject) -> Bool
18 | }
19 |
20 | final class VoightKampffTest: RealnessTesting {
21 | func testRealness(_ testSubject: TestSubject) -> Bool {
22 | return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
23 | }
24 | }
25 |
26 | final class GeneticTest: RealnessTesting {
27 | func testRealness(_ testSubject: TestSubject) -> Bool {
28 | return testSubject.isOrganic
29 | }
30 | }
31 |
32 | final class BladeRunner {
33 | private let strategy: RealnessTesting
34 |
35 | init(test: RealnessTesting) {
36 | self.strategy = test
37 | }
38 |
39 | func testIfAndroid(_ testSubject: TestSubject) -> Bool {
40 | return !strategy.testRealness(testSubject)
41 | }
42 | }
43 |
44 | /*:
45 | ### Usage
46 | */
47 |
48 | let rachel = TestSubject(pupilDiameter: 30.2,
49 | blushResponse: 0.3,
50 | isOrganic: false)
51 |
52 | // Deckard is using a traditional test
53 | let deckard = BladeRunner(test: VoightKampffTest())
54 | let isRachelAndroid = deckard.testIfAndroid(rachel)
55 |
56 | // Gaff is using a very precise method
57 | let gaff = BladeRunner(test: GeneticTest())
58 | let isDeckardAndroid = gaff.testIfAndroid(rachel)
59 |
--------------------------------------------------------------------------------
/source/behavioral/template_method.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 📝 Template Method
3 | -----------
4 |
5 | The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.
6 |
7 | ### Example
8 | */
9 | protocol Garden {
10 | func prepareSoil()
11 | func plantSeeds()
12 | func waterPlants()
13 | func prepareGarden()
14 | }
15 |
16 | extension Garden {
17 |
18 | func prepareGarden() {
19 | prepareSoil()
20 | plantSeeds()
21 | waterPlants()
22 | }
23 | }
24 |
25 | final class RoseGarden: Garden {
26 |
27 | func prepare() {
28 | prepareGarden()
29 | }
30 |
31 | func prepareSoil() {
32 | print ("prepare soil for rose garden")
33 | }
34 |
35 | func plantSeeds() {
36 | print ("plant seeds for rose garden")
37 | }
38 |
39 | func waterPlants() {
40 | print ("water the rose garden")
41 | }
42 | }
43 |
44 | /*:
45 | ### Usage
46 | */
47 |
48 | let roseGarden = RoseGarden()
49 | roseGarden.prepare()
50 |
--------------------------------------------------------------------------------
/source/behavioral/visitor.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🏃 Visitor
3 | ----------
4 |
5 | The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
6 |
7 | ### Example
8 | */
9 | protocol PlanetVisitor {
10 | func visit(planet: PlanetAlderaan)
11 | func visit(planet: PlanetCoruscant)
12 | func visit(planet: PlanetTatooine)
13 | func visit(planet: MoonJedha)
14 | }
15 |
16 | protocol Planet {
17 | func accept(visitor: PlanetVisitor)
18 | }
19 |
20 | final class MoonJedha: Planet {
21 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
22 | }
23 |
24 | final class PlanetAlderaan: Planet {
25 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
26 | }
27 |
28 | final class PlanetCoruscant: Planet {
29 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
30 | }
31 |
32 | final class PlanetTatooine: Planet {
33 | func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
34 | }
35 |
36 | final class NameVisitor: PlanetVisitor {
37 | var name = ""
38 |
39 | func visit(planet: PlanetAlderaan) { name = "Alderaan" }
40 | func visit(planet: PlanetCoruscant) { name = "Coruscant" }
41 | func visit(planet: PlanetTatooine) { name = "Tatooine" }
42 | func visit(planet: MoonJedha) { name = "Jedha" }
43 | }
44 |
45 | /*:
46 | ### Usage
47 | */
48 | let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
49 |
50 | let names = planets.map { (planet: Planet) -> String in
51 | let visitor = NameVisitor()
52 | planet.accept(visitor: visitor)
53 |
54 | return visitor.name
55 | }
56 |
57 | names
58 |
--------------------------------------------------------------------------------
/source/contents.md:
--------------------------------------------------------------------------------
1 |
2 | ## Table of Contents
3 |
4 | * [Behavioral](Behavioral)
5 | * [Creational](Creational)
6 | * [Structural](Structural)
7 |
--------------------------------------------------------------------------------
/source/contentsReadme.md:
--------------------------------------------------------------------------------
1 |
2 | ## Table of Contents
3 |
4 | | [Behavioral](#behavioral) | [Creational](#creational) | [Structural](#structural) |
5 | | ------------------------------------------------------ | ---------------------------------------- | ---------------------------------------- |
6 | | [🐝 Chain Of Responsibility](#-chain-of-responsibility) | [🌰 Abstract Factory](#-abstract-factory) | [🔌 Adapter](#-adapter) |
7 | | [👫 Command](#-command) | [👷 Builder](#-builder) | [🌉 Bridge](#-bridge) |
8 | | [🎶 Interpreter](#-interpreter) | [🏭 Factory Method](#-factory-method) | [🌿 Composite](#-composite) |
9 | | [🍫 Iterator](#-iterator) | [🔂 Monostate](#-monostate) | [🍧 Decorator](#-decorator) |
10 | | [💐 Mediator](#-mediator) | [🃏 Prototype](#-prototype) | [🎁 Façade](#-fa-ade) |
11 | | [💾 Memento](#-memento) | [💍 Singleton](#-singleton) | [🍃 Flyweight](#-flyweight) |
12 | | [👓 Observer](#-observer) | | [☔ Protection Proxy](#-protection-proxy) |
13 | | [🐉 State](#-state) | | [🍬 Virtual Proxy](#-virtual-proxy) |
14 | | [💡 Strategy](#-strategy) | | |
15 | | [🏃 Visitor](#-visitor) | | |
16 | | [📝 Template Method](#-template-method) | | |
17 |
18 |
--------------------------------------------------------------------------------
/source/creational/abstract_factory.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🌰 Abstract Factory
3 | -------------------
4 |
5 | The abstract factory pattern is used to provide a client with a set of related or dependant objects.
6 | The "family" of objects created by the factory are determined at run-time.
7 |
8 | ### Example
9 |
10 | Protocols
11 | */
12 |
13 | protocol BurgerDescribing {
14 | var ingredients: [String] { get }
15 | }
16 |
17 | struct CheeseBurger: BurgerDescribing {
18 | let ingredients: [String]
19 | }
20 |
21 | protocol BurgerMaking {
22 | func make() -> BurgerDescribing
23 | }
24 |
25 | // Number implementations with factory methods
26 |
27 | final class BigKahunaBurger: BurgerMaking {
28 | func make() -> BurgerDescribing {
29 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
30 | }
31 | }
32 |
33 | final class JackInTheBox: BurgerMaking {
34 | func make() -> BurgerDescribing {
35 | return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
36 | }
37 | }
38 |
39 | /*:
40 | Abstract factory
41 | */
42 |
43 | enum BurgerFactoryType: BurgerMaking {
44 |
45 | case bigKahuna
46 | case jackInTheBox
47 |
48 | func make() -> BurgerDescribing {
49 | switch self {
50 | case .bigKahuna:
51 | return BigKahunaBurger().make()
52 | case .jackInTheBox:
53 | return JackInTheBox().make()
54 | }
55 | }
56 | }
57 | /*:
58 | ### Usage
59 | */
60 | let bigKahuna = BurgerFactoryType.bigKahuna.make()
61 | let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
62 |
--------------------------------------------------------------------------------
/source/creational/builder.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 👷 Builder
3 | ----------
4 |
5 | The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm.
6 | An external class controls the construction algorithm.
7 |
8 | ### Example
9 | */
10 | final class DeathStarBuilder {
11 |
12 | var x: Double?
13 | var y: Double?
14 | var z: Double?
15 |
16 | typealias BuilderClosure = (DeathStarBuilder) -> ()
17 |
18 | init(buildClosure: BuilderClosure) {
19 | buildClosure(self)
20 | }
21 | }
22 |
23 | struct DeathStar : CustomStringConvertible {
24 |
25 | let x: Double
26 | let y: Double
27 | let z: Double
28 |
29 | init?(builder: DeathStarBuilder) {
30 |
31 | if let x = builder.x, let y = builder.y, let z = builder.z {
32 | self.x = x
33 | self.y = y
34 | self.z = z
35 | } else {
36 | return nil
37 | }
38 | }
39 |
40 | var description:String {
41 | return "Death Star at (x:\(x) y:\(y) z:\(z))"
42 | }
43 | }
44 | /*:
45 | ### Usage
46 | */
47 | let empire = DeathStarBuilder { builder in
48 | builder.x = 0.1
49 | builder.y = 0.2
50 | builder.z = 0.3
51 | }
52 |
53 | let deathStar = DeathStar(builder:empire)
54 |
--------------------------------------------------------------------------------
/source/creational/factory.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🏭 Factory Method
3 | -----------------
4 |
5 | The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
6 |
7 | ### Example
8 | */
9 | protocol CurrencyDescribing {
10 | var symbol: String { get }
11 | var code: String { get }
12 | }
13 |
14 | final class Euro: CurrencyDescribing {
15 | var symbol: String {
16 | return "€"
17 | }
18 |
19 | var code: String {
20 | return "EUR"
21 | }
22 | }
23 |
24 | final class UnitedStatesDolar: CurrencyDescribing {
25 | var symbol: String {
26 | return "$"
27 | }
28 |
29 | var code: String {
30 | return "USD"
31 | }
32 | }
33 |
34 | enum Country {
35 | case unitedStates
36 | case spain
37 | case uk
38 | case greece
39 | }
40 |
41 | enum CurrencyFactory {
42 | static func currency(for country: Country) -> CurrencyDescribing? {
43 |
44 | switch country {
45 | case .spain, .greece:
46 | return Euro()
47 | case .unitedStates:
48 | return UnitedStatesDolar()
49 | default:
50 | return nil
51 | }
52 |
53 | }
54 | }
55 | /*:
56 | ### Usage
57 | */
58 | let noCurrencyCode = "No Currency Code Available"
59 |
60 | CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
61 | CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
62 | CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
63 | CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
64 |
--------------------------------------------------------------------------------
/source/creational/header.md:
--------------------------------------------------------------------------------
1 |
2 | Creational
3 | ==========
4 |
5 | > In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
6 | >
7 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)
8 |
--------------------------------------------------------------------------------
/source/creational/monostate.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🔂 Monostate
3 | ------------
4 |
5 | The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints.
6 | So in that case, monostate saves the state as static instead of the entire instance as a singleton.
7 | [SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
8 |
9 | ### Example:
10 | */
11 | class Settings {
12 |
13 | enum Theme {
14 | case `default`
15 | case old
16 | case new
17 | }
18 |
19 | private static var theme: Theme?
20 |
21 | var currentTheme: Theme {
22 | get { Settings.theme ?? .default }
23 | set(newTheme) { Settings.theme = newTheme }
24 | }
25 | }
26 | /*:
27 | ### Usage:
28 | */
29 |
30 | import SwiftUI
31 |
32 | // When change the theme
33 | let settings = Settings() // Starts using theme .old
34 | settings.currentTheme = .new // Change theme to .new
35 |
36 | // On screen 1
37 | let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
38 |
39 | // On screen 2
40 | let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
41 |
--------------------------------------------------------------------------------
/source/creational/prototype.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🃏 Prototype
3 | ------------
4 |
5 | The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
6 | This practise is particularly useful when the construction of a new object is inefficient.
7 |
8 | ### Example
9 | */
10 | class MoonWorker {
11 |
12 | let name: String
13 | var health: Int = 100
14 |
15 | init(name: String) {
16 | self.name = name
17 | }
18 |
19 | func clone() -> MoonWorker {
20 | return MoonWorker(name: name)
21 | }
22 | }
23 | /*:
24 | ### Usage
25 | */
26 | let prototype = MoonWorker(name: "Sam Bell")
27 |
28 | var bell1 = prototype.clone()
29 | bell1.health = 12
30 |
31 | var bell2 = prototype.clone()
32 | bell2.health = 23
33 |
34 | var bell3 = prototype.clone()
35 | bell3.health = 0
36 |
--------------------------------------------------------------------------------
/source/creational/singleton.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 💍 Singleton
3 | ------------
4 |
5 | The singleton pattern ensures that only one object of a particular class is ever created.
6 | All further references to objects of the singleton class refer to the same underlying instance.
7 | There are very few applications, do not overuse this pattern!
8 |
9 | ### Example:
10 | */
11 | final class ElonMusk {
12 |
13 | static let shared = ElonMusk()
14 |
15 | private init() {
16 | // Private initialization to ensure just one instance is created.
17 | }
18 | }
19 | /*:
20 | ### Usage:
21 | */
22 | let elon = ElonMusk.shared // There is only one Elon Musk folks.
23 |
--------------------------------------------------------------------------------
/source/endComment:
--------------------------------------------------------------------------------
1 |
2 | */
--------------------------------------------------------------------------------
/source/endSwiftCode:
--------------------------------------------------------------------------------
1 | ```
2 |
3 |
--------------------------------------------------------------------------------
/source/footer.md:
--------------------------------------------------------------------------------
1 |
2 | Info
3 | ====
4 |
5 | 📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)
6 |
--------------------------------------------------------------------------------
/source/imports.swift:
--------------------------------------------------------------------------------
1 |
2 | import Foundation
3 |
--------------------------------------------------------------------------------
/source/startComment:
--------------------------------------------------------------------------------
1 | /*:
2 |
--------------------------------------------------------------------------------
/source/startSwiftCode:
--------------------------------------------------------------------------------
1 |
2 |
3 | ```swift
--------------------------------------------------------------------------------
/source/structural/adapter.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🔌 Adapter
3 | ----------
4 |
5 | The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
6 |
7 | ### Example
8 | */
9 | protocol NewDeathStarSuperLaserAiming {
10 | var angleV: Double { get }
11 | var angleH: Double { get }
12 | }
13 | /*:
14 | **Adaptee**
15 | */
16 | struct OldDeathStarSuperlaserTarget {
17 | let angleHorizontal: Float
18 | let angleVertical: Float
19 |
20 | init(angleHorizontal: Float, angleVertical: Float) {
21 | self.angleHorizontal = angleHorizontal
22 | self.angleVertical = angleVertical
23 | }
24 | }
25 | /*:
26 | **Adapter**
27 | */
28 | struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
29 |
30 | private let target: OldDeathStarSuperlaserTarget
31 |
32 | var angleV: Double {
33 | return Double(target.angleVertical)
34 | }
35 |
36 | var angleH: Double {
37 | return Double(target.angleHorizontal)
38 | }
39 |
40 | init(_ target: OldDeathStarSuperlaserTarget) {
41 | self.target = target
42 | }
43 | }
44 | /*:
45 | ### Usage
46 | */
47 | let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
48 | let newFormat = NewDeathStarSuperlaserTarget(target)
49 |
50 | newFormat.angleH
51 | newFormat.angleV
52 |
--------------------------------------------------------------------------------
/source/structural/bridge.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🌉 Bridge
3 | ----------
4 |
5 | The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
6 |
7 | ### Example
8 | */
9 | protocol Switch {
10 | var appliance: Appliance { get set }
11 | func turnOn()
12 | }
13 |
14 | protocol Appliance {
15 | func run()
16 | }
17 |
18 | final class RemoteControl: Switch {
19 | var appliance: Appliance
20 |
21 | func turnOn() {
22 | self.appliance.run()
23 | }
24 |
25 | init(appliance: Appliance) {
26 | self.appliance = appliance
27 | }
28 | }
29 |
30 | final class TV: Appliance {
31 | func run() {
32 | print("tv turned on");
33 | }
34 | }
35 |
36 | final class VacuumCleaner: Appliance {
37 | func run() {
38 | print("vacuum cleaner turned on")
39 | }
40 | }
41 | /*:
42 | ### Usage
43 | */
44 | let tvRemoteControl = RemoteControl(appliance: TV())
45 | tvRemoteControl.turnOn()
46 |
47 | let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
48 | fancyVacuumCleanerRemoteControl.turnOn()
49 |
--------------------------------------------------------------------------------
/source/structural/composite.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🌿 Composite
3 | -------------
4 |
5 | The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
6 |
7 | ### Example
8 |
9 | Component
10 | */
11 | protocol Shape {
12 | func draw(fillColor: String)
13 | }
14 | /*:
15 | Leafs
16 | */
17 | final class Square: Shape {
18 | func draw(fillColor: String) {
19 | print("Drawing a Square with color \(fillColor)")
20 | }
21 | }
22 |
23 | final class Circle: Shape {
24 | func draw(fillColor: String) {
25 | print("Drawing a circle with color \(fillColor)")
26 | }
27 | }
28 |
29 | /*:
30 | Composite
31 | */
32 | final class Whiteboard: Shape {
33 |
34 | private lazy var shapes = [Shape]()
35 |
36 | init(_ shapes: Shape...) {
37 | self.shapes = shapes
38 | }
39 |
40 | func draw(fillColor: String) {
41 | for shape in self.shapes {
42 | shape.draw(fillColor: fillColor)
43 | }
44 | }
45 | }
46 | /*:
47 | ### Usage:
48 | */
49 | var whiteboard = Whiteboard(Circle(), Square())
50 | whiteboard.draw(fillColor: "Red")
51 |
--------------------------------------------------------------------------------
/source/structural/decorator.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍧 Decorator
3 | ------------
4 |
5 | The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class.
6 | This provides a flexible alternative to using inheritance to modify behaviour.
7 |
8 | ### Example
9 | */
10 | protocol CostHaving {
11 | var cost: Double { get }
12 | }
13 |
14 | protocol IngredientsHaving {
15 | var ingredients: [String] { get }
16 | }
17 |
18 | typealias BeverageDataHaving = CostHaving & IngredientsHaving
19 |
20 | struct SimpleCoffee: BeverageDataHaving {
21 | let cost: Double = 1.0
22 | let ingredients = ["Water", "Coffee"]
23 | }
24 |
25 | protocol BeverageHaving: BeverageDataHaving {
26 | var beverage: BeverageDataHaving { get }
27 | }
28 |
29 | struct Milk: BeverageHaving {
30 |
31 | let beverage: BeverageDataHaving
32 |
33 | var cost: Double {
34 | return beverage.cost + 0.5
35 | }
36 |
37 | var ingredients: [String] {
38 | return beverage.ingredients + ["Milk"]
39 | }
40 | }
41 |
42 | struct WhipCoffee: BeverageHaving {
43 |
44 | let beverage: BeverageDataHaving
45 |
46 | var cost: Double {
47 | return beverage.cost + 0.5
48 | }
49 |
50 | var ingredients: [String] {
51 | return beverage.ingredients + ["Whip"]
52 | }
53 | }
54 | /*:
55 | ### Usage:
56 | */
57 | var someCoffee: BeverageDataHaving = SimpleCoffee()
58 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
59 | someCoffee = Milk(beverage: someCoffee)
60 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
61 | someCoffee = WhipCoffee(beverage: someCoffee)
62 | print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
63 |
--------------------------------------------------------------------------------
/source/structural/facade.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🎁 Façade
3 | ---------
4 |
5 | The facade pattern is used to define a simplified interface to a more complex subsystem.
6 |
7 | ### Example
8 | */
9 | final class Defaults {
10 |
11 | private let defaults: UserDefaults
12 |
13 | init(defaults: UserDefaults = .standard) {
14 | self.defaults = defaults
15 | }
16 |
17 | subscript(key: String) -> String? {
18 | get {
19 | return defaults.string(forKey: key)
20 | }
21 |
22 | set {
23 | defaults.set(newValue, forKey: key)
24 | }
25 | }
26 | }
27 | /*:
28 | ### Usage
29 | */
30 | let storage = Defaults()
31 |
32 | // Store
33 | storage["Bishop"] = "Disconnect me. I’d rather be nothing"
34 |
35 | // Read
36 | storage["Bishop"]
37 |
--------------------------------------------------------------------------------
/source/structural/flyweight.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | ## 🍃 Flyweight
3 | The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
4 | ### Example
5 | */
6 | // Instances of SpecialityCoffee will be the Flyweights
7 | struct SpecialityCoffee {
8 | let origin: String
9 | }
10 |
11 | protocol CoffeeSearching {
12 | func search(origin: String) -> SpecialityCoffee?
13 | }
14 |
15 | // Menu acts as a factory and cache for SpecialityCoffee flyweight objects
16 | final class Menu: CoffeeSearching {
17 |
18 | private var coffeeAvailable: [String: SpecialityCoffee] = [:]
19 |
20 | func search(origin: String) -> SpecialityCoffee? {
21 | if coffeeAvailable.index(forKey: origin) == nil {
22 | coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
23 | }
24 |
25 | return coffeeAvailable[origin]
26 | }
27 | }
28 |
29 | final class CoffeeShop {
30 | private var orders: [Int: SpecialityCoffee] = [:]
31 | private let menu: CoffeeSearching
32 |
33 | init(menu: CoffeeSearching) {
34 | self.menu = menu
35 | }
36 |
37 | func takeOrder(origin: String, table: Int) {
38 | orders[table] = menu.search(origin: origin)
39 | }
40 |
41 | func serve() {
42 | for (table, origin) in orders {
43 | print("Serving \(origin) to table \(table)")
44 | }
45 | }
46 | }
47 | /*:
48 | ### Usage
49 | */
50 | let coffeeShop = CoffeeShop(menu: Menu())
51 |
52 | coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
53 | coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
54 |
55 | coffeeShop.serve()
56 |
--------------------------------------------------------------------------------
/source/structural/header.md:
--------------------------------------------------------------------------------
1 |
2 | Structural
3 | ==========
4 |
5 | >In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
6 | >
7 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)
8 |
--------------------------------------------------------------------------------
/source/structural/protection_proxy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | ☔ Protection Proxy
3 | ------------------
4 |
5 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
6 | Protection proxy is restricting access.
7 |
8 | ### Example
9 | */
10 | protocol DoorOpening {
11 | func open(doors: String) -> String
12 | }
13 |
14 | final class HAL9000: DoorOpening {
15 | func open(doors: String) -> String {
16 | return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
17 | }
18 | }
19 |
20 | final class CurrentComputer: DoorOpening {
21 | private var computer: HAL9000!
22 |
23 | func authenticate(password: String) -> Bool {
24 |
25 | guard password == "pass" else {
26 | return false
27 | }
28 |
29 | computer = HAL9000()
30 |
31 | return true
32 | }
33 |
34 | func open(doors: String) -> String {
35 |
36 | guard computer != nil else {
37 | return "Access Denied. I'm afraid I can't do that."
38 | }
39 |
40 | return computer.open(doors: doors)
41 | }
42 | }
43 | /*:
44 | ### Usage
45 | */
46 | let computer = CurrentComputer()
47 | let podBay = "Pod Bay Doors"
48 |
49 | computer.open(doors: podBay)
50 |
51 | computer.authenticate(password: "pass")
52 | computer.open(doors: podBay)
53 |
--------------------------------------------------------------------------------
/source/structural/virtual_proxy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🍬 Virtual Proxy
3 | ----------------
4 |
5 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
6 | Virtual proxy is used for loading object on demand.
7 |
8 | ### Example
9 | */
10 | protocol HEVSuitMedicalAid {
11 | func administerMorphine() -> String
12 | }
13 |
14 | final class HEVSuit: HEVSuitMedicalAid {
15 | func administerMorphine() -> String {
16 | return "Morphine administered."
17 | }
18 | }
19 |
20 | final class HEVSuitHumanInterface: HEVSuitMedicalAid {
21 |
22 | lazy private var physicalSuit: HEVSuit = HEVSuit()
23 |
24 | func administerMorphine() -> String {
25 | return physicalSuit.administerMorphine()
26 | }
27 | }
28 | /*:
29 | ### Usage
30 | */
31 | let humanInterface = HEVSuitHumanInterface()
32 | humanInterface.administerMorphine()
33 |
--------------------------------------------------------------------------------