├── Design-Patterns.zip
├── PULL_REQUEST_TEMPLATE.md
├── source
├── footer.swift
├── structural
│ ├── _title.swift
│ ├── Proxy.swift
│ ├── facade.swift
│ ├── decorator.swift
│ ├── bridge.swift
│ ├── composite.swift
│ ├── adapter.swift
│ └── flyweight.swift
├── behavioral
│ ├── _title.swift
│ ├── Template-Method.swift
│ ├── iterator.swift
│ ├── strategy.swift
│ ├── memento.swift
│ ├── state.swift
│ ├── interpreter.swift
│ ├── command.swift
│ ├── Chain-Of-Responsibility.swift
│ ├── visitor.swift
│ ├── observer.swift
│ └── mediator.swift
├── creational
│ ├── singleton.swift
│ ├── _title.swift
│ ├── prototype.swift
│ ├── factory.swift
│ ├── builder.swift
│ └── Abstract-Factory.swift
└── header.swift
├── GENERATE.md
├── Behavioral.playground
├── playground.xcworkspace
│ └── contents.xcworkspacedata
├── Pages
│ ├── Interpreter.xcplaygroundpage
│ │ ├── timeline.xctimeline
│ │ └── Contents.swift
│ ├── Template-method.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Iterator.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Strategy.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Memento.xcplaygroundpage
│ │ └── Contents.swift
│ ├── State.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Chain-Of-Responsibility.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Command.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Observer.xcplaygroundpage
│ │ └── Contents.swift
│ ├── Visitor.xcplaygroundpage
│ │ └── Contents.swift
│ └── Mediator.xcplaygroundpage
│ │ └── Contents.swift
└── contents.xcplayground
├── Creational.playground
├── playground.xcworkspace
│ └── contents.xcworkspacedata
├── contents.xcplayground
└── Pages
│ ├── Singleton.xcplaygroundpage
│ └── Contents.swift
│ ├── Prototype.xcplaygroundpage
│ └── Contents.swift
│ ├── Factory.xcplaygroundpage
│ └── Contents.swift
│ ├── Builder.xcplaygroundpage
│ └── Contents.swift
│ └── Abstract-Factory.xcplaygroundpage
│ └── Contents.swift
├── Structural.playground
├── playground.xcworkspace
│ └── contents.xcworkspacedata
├── contents.xcplayground
└── Pages
│ ├── Proxy.xcplaygroundpage
│ └── Contents.swift
│ ├── Facade.xcplaygroundpage
│ └── Contents.swift
│ ├── Decorator.xcplaygroundpage
│ └── Contents.swift
│ ├── Bridge.xcplaygroundpage
│ └── Contents.swift
│ ├── Composite.xcplaygroundpage
│ └── Contents.swift
│ ├── Adapter.xcplaygroundpage
│ └── Contents.swift
│ └── Flyweight.xcplaygroundpage
│ └── Contents.swift
├── Design-Patterns.playground
├── playground.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ │ └── Design-Patterns.xccheckout
├── contents.xcplayground
└── Pages
│ ├── Creational.xcplaygroundpage
│ └── Contents.swift
│ ├── Structural.xcplaygroundpage
│ └── Contents.swift
│ └── Behavioral.xcplaygroundpage
│ └── Contents.swift
├── .gitignore
├── generate-playground.sh
├── LICENSE
└── README.md
/Design-Patterns.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zsergey/Design-Patterns-In-Swift/HEAD/Design-Patterns.zip
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | - [ ] Do not change the `.playground` nor `README.md` manually.
4 | - [ ] Go to `/source` and edit .swift files.
5 | - [ ] Run: `generate-playground.sh`
--------------------------------------------------------------------------------
/source/footer.swift:
--------------------------------------------------------------------------------
1 | /*:
2 |
3 | Info
4 | ====
5 |
6 | 📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)
7 |
8 | */
9 |
--------------------------------------------------------------------------------
/GENERATE.md:
--------------------------------------------------------------------------------
1 | How to generate playground and zip
2 | ==================================
3 |
4 | In Terminal type:
5 |
6 | every time:
7 |
8 | ```bash
9 | ./generate-playground.sh
10 | ```
11 |
12 | 👍
--------------------------------------------------------------------------------
/Behavioral.playground/playground.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Creational.playground/playground.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Structural.playground/playground.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/playground.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # CocoaPods
2 | #
3 | # We recommend against adding the Pods directory to your .gitignore. However
4 | # you should judge for yourself, the pros and cons are mentioned at:
5 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control?
6 | #
7 | # Pods/
8 |
9 | .DS_Store
10 | UserInterfaceState.xcuserstate
11 |
--------------------------------------------------------------------------------
/source/structural/_title.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 |
--------------------------------------------------------------------------------
/Creational.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/source/behavioral/_title.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 |
--------------------------------------------------------------------------------
/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 | struct Game {
12 | static let sharedGame = Game()
13 |
14 | private init() {
15 |
16 | }
17 | }
18 | /*:
19 | ### Usage:
20 | */
21 | let game = Game.sharedGame
22 |
--------------------------------------------------------------------------------
/source/creational/_title.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Interpreter.xcplaygroundpage/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Behavioral.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/source/header.swift:
--------------------------------------------------------------------------------
1 |
2 | Design Patterns implemented in Swift 3.1
3 | ========================================
4 | A short cheat-sheet with Xcode 8.3.2 Playground ([Design-Patterns.zip](https://raw.githubusercontent.com/zsergey/Design-Patterns-In-Swift/master/Design-Patterns.zip)).
5 |
6 | 👷 Project maintained by: [@zsergey](http://twitter.com/zsergey) (Sergey Zapuhlyak)
7 |
8 | 🚀 How to generate README, Playground and zip from source: [GENERATE.md](https://github.com/zsergey/Design-Patterns-In-Swift/blob/master/GENERATE.md)
9 |
10 | ## Table of Contents
11 |
12 | * [Behavioral](#behavioral)
13 | * [Creational](#creational)
14 | * [Structural](#structural)
15 |
16 | */
17 |
--------------------------------------------------------------------------------
/source/behavioral/Template-Method.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | 🐾 Template Method
3 | ----------
4 |
5 | The template method pattern is used to define the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.
6 |
7 | ### Example
8 | */
9 | protocol WebsiteTemplate {
10 | func showPageContent()
11 | }
12 |
13 | extension WebsiteTemplate {
14 | func showPage() {
15 | print("Header")
16 | showPageContent()
17 | print("Footer")
18 | }
19 | }
20 |
21 | struct WelcomePage: WebsiteTemplate {
22 | func showPageContent() {
23 | print("Welcome")
24 | }
25 | }
26 |
27 | struct NewsPage: WebsiteTemplate {
28 | func showPageContent() {
29 | print("News")
30 | }
31 | }
32 | /*:
33 | ### Usage
34 | */
35 | let welcomePage = WelcomePage()
36 | welcomePage.showPage()
37 | print("")
38 |
39 | let newsPage = NewsPage()
40 | newsPage.showPage()
41 |
--------------------------------------------------------------------------------
/source/structural/Proxy.swift:
--------------------------------------------------------------------------------
1 | /*:
2 | ☔ Proxy
3 | ------------------
4 |
5 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
6 |
7 | ### Example
8 | */
9 | protocol Project {
10 | func run()
11 | }
12 |
13 | struct RealProject: Project {
14 | var url: String
15 |
16 | func load() {
17 | print("Loading project from url \(url) ...")
18 | }
19 |
20 | init(url: String) {
21 | self.url = url
22 | load()
23 | }
24 |
25 | func run() {
26 | print("Running project \(url) ...")
27 | }
28 | }
29 |
30 | class ProxyProject: Project {
31 | var url: String
32 | var realProject: RealProject?
33 |
34 | func run() {
35 | if realProject == nil {
36 | realProject = RealProject(url: url)
37 | }
38 | realProject!.run()
39 | }
40 |
41 | init(url: String) {
42 | self.url = url
43 | }
44 | }
45 | /*:
46 | ### Usage
47 | */
48 | var project = ProxyProject(url: "https://github.com/zsergey/realProject")
49 | project.run()
50 |
--------------------------------------------------------------------------------
/Structural.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Creational.playground/Pages/Singleton.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 💍 Singleton
13 | ------------
14 |
15 | The singleton pattern ensures that only one object of a particular class is ever created.
16 | All further references to objects of the singleton class refer to the same underlying instance.
17 | There are very few applications, do not overuse this pattern!
18 |
19 | ### Example:
20 | */
21 | struct Game {
22 | static let sharedGame = Game()
23 |
24 | private init() {
25 |
26 | }
27 | }
28 | /*:
29 | ### Usage:
30 | */
31 | let game = Game.sharedGame
32 |
--------------------------------------------------------------------------------
/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 | protocol Copyable {
11 | func copy() -> Any
12 | }
13 |
14 | struct Project: Copyable {
15 | var id: Int
16 | var name: String
17 | var source: String
18 |
19 | func copy() -> Any {
20 | let object = Project(id: id, name: name, source: source)
21 | return object
22 | }
23 | }
24 |
25 | struct ProjectFactory {
26 | var project: Project
27 | func cloneProject() -> Project {
28 | return project.copy() as! Project
29 | }
30 | }
31 | /*:
32 | ### Usage
33 | */
34 | let master = Project(id: 1, name: "Playground.swift", source: "let sourceCode = SourceCode()")
35 | let factory = ProjectFactory(project: master)
36 | let masterClone = factory.cloneProject()
37 | /*:
38 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Prototype)
39 | */
40 |
--------------------------------------------------------------------------------
/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 | class Job {
10 | func doJob() {
11 | print("Job is progress...")
12 | }
13 | }
14 |
15 | class BugTracker {
16 | var isActiveSprint = false
17 |
18 | func startSprint() {
19 | print("Sprint is active")
20 | isActiveSprint = true
21 | }
22 |
23 | func stopSprint() {
24 | print("Sprint is not active")
25 | isActiveSprint = false
26 | }
27 | }
28 |
29 | class Developer {
30 | func doJobBeforeDeadline(bugTracker: BugTracker) {
31 | if bugTracker.isActiveSprint {
32 | print("Developer is solving problems...")
33 | } else {
34 | print("Developer is reading the news...")
35 | }
36 | }
37 | }
38 |
39 | class Workflow {
40 | let developer = Developer()
41 | let job = Job()
42 | let bugTracker = BugTracker()
43 | func solveProblems() {
44 | job.doJob()
45 | bugTracker.startSprint()
46 | developer.doJobBeforeDeadline(bugTracker: bugTracker)
47 | }
48 | }
49 | /*:
50 | ### Usage
51 | */
52 | let workflow = Workflow()
53 | workflow.solveProblems()
54 |
--------------------------------------------------------------------------------
/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 Developer {
11 | func makeJob() -> String
12 | }
13 |
14 | struct SwiftDeveloper: Developer {
15 | func makeJob() -> String {
16 | return "Write Swift code"
17 | }
18 | }
19 |
20 | class DeveloperDecorator: Developer {
21 | var developer: Developer
22 | func makeJob() -> String {
23 | return developer.makeJob()
24 | }
25 | init(developer: Developer) {
26 | self.developer = developer
27 | }
28 | }
29 |
30 | class SeniorSwiftDeveloper: DeveloperDecorator {
31 | let codeReview = "Make code review"
32 | override func makeJob() -> String {
33 | return super.makeJob() + " & " + codeReview
34 | }
35 | }
36 |
37 | class SwiftTeamLead: DeveloperDecorator {
38 | let sendWeekReport = "Send week report"
39 | override func makeJob() -> String {
40 | return super.makeJob() + " & " + sendWeekReport
41 | }
42 | }
43 | /*:
44 | ### Usage:
45 | */
46 | let developer = SwiftTeamLead(developer: SeniorSwiftDeveloper(developer: SwiftDeveloper()))
47 | print(developer.makeJob())
48 |
--------------------------------------------------------------------------------
/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 | protocol Iterator {
10 | func hasNext() -> Bool
11 | mutating func next() -> String
12 | }
13 |
14 | protocol Collection {
15 | func getIterator() -> Iterator
16 | }
17 |
18 | struct SwiftDeveloper: Collection {
19 | var name: String
20 | var skills: [String]
21 |
22 | private struct SkillIterator: Iterator {
23 | var index: Int
24 | var data: [String]
25 | func hasNext() -> Bool {
26 | return index < data.count
27 | }
28 | mutating func next() -> String {
29 | let result = data[index]
30 | index = index + 1
31 | return result
32 | }
33 | }
34 |
35 | func getIterator() -> Iterator {
36 | return SkillIterator(index: 0, data: skills)
37 | }
38 | }
39 | /*:
40 | ### Usage
41 | */
42 | let skills = ["Swift", "ObjC", "Sketch", "PM"]
43 | let swiftDeveloper = SwiftDeveloper(name: "Sergey Zapuhlyak", skills: skills)
44 | var iterator = swiftDeveloper.getIterator()
45 | print("Developer \(swiftDeveloper.name)")
46 | print("Skills")
47 | while iterator.hasNext() {
48 | print("\(iterator.next())")
49 | }
50 |
--------------------------------------------------------------------------------
/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 Developer {
10 | func writeCode()
11 | }
12 |
13 | protocol Program {
14 | var developer: Developer { get set }
15 | func develop()
16 | }
17 |
18 | struct SwiftDeveloper: Developer {
19 | func writeCode() {
20 | print("Swift Developer writes Swift code...")
21 | }
22 | }
23 |
24 | struct ObjCDeveloper: Developer {
25 | func writeCode() {
26 | print("ObjC Developer writes Objective-C code...")
27 | }
28 | }
29 |
30 | struct BankSystem: Program {
31 | var developer: Developer
32 |
33 | func develop() {
34 | print("Bank System development in progress...")
35 | developer.writeCode()
36 | }
37 | }
38 |
39 | struct StockExchange: Program {
40 | var developer: Developer
41 |
42 | func develop() {
43 | print("Stock Exchange development in progress...")
44 | developer.writeCode()
45 | }
46 | }
47 | /*:
48 | ### Usage
49 | */
50 | let programs: [Program] = [BankSystem(developer: ObjCDeveloper()),
51 | StockExchange(developer: SwiftDeveloper())]
52 | for program in programs {
53 | program.develop()
54 | }
55 |
--------------------------------------------------------------------------------
/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 | protocol Activity {
10 | func justDoIt()
11 | }
12 |
13 | struct Coding: Activity {
14 | func justDoIt() {
15 | print("Writing code...")
16 | }
17 | }
18 |
19 | struct Reading: Activity {
20 | func justDoIt() {
21 | print("Reading book...")
22 | }
23 | }
24 |
25 | struct Sleeping: Activity {
26 | func justDoIt() {
27 | print("Sleeping...")
28 | }
29 | }
30 |
31 | struct Training: Activity {
32 | func justDoIt() {
33 | print("Training...")
34 | }
35 | }
36 |
37 | struct Developer {
38 | var activity: Activity
39 |
40 | func executeActivity() {
41 | activity.justDoIt()
42 | }
43 | }
44 | /*:
45 | ### Usage
46 | */
47 | var developer = Developer(activity: Sleeping())
48 | developer.executeActivity()
49 |
50 | developer.activity = Training()
51 | developer.executeActivity()
52 |
53 | developer.activity = Coding()
54 | developer.executeActivity()
55 |
56 | developer.activity = Reading()
57 | developer.executeActivity()
58 |
59 | developer.activity = Sleeping()
60 | developer.executeActivity()
61 | /*:
62 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy)
63 | */
64 |
--------------------------------------------------------------------------------
/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 Developer {
10 | func writeCode()
11 | }
12 |
13 | struct ObjCDeveloper: Developer {
14 | func writeCode() {
15 | print("ObjC developer writes Objective C code...")
16 | }
17 | }
18 |
19 | struct SwiftDeveloper: Developer {
20 | func writeCode() {
21 | print("Swift developer writes Swift code...")
22 | }
23 | }
24 |
25 | protocol DeveloperFactory {
26 | func newDeveloper() -> Developer
27 | }
28 |
29 | struct ObjCDeveloperFactory: DeveloperFactory {
30 | func newDeveloper() -> Developer {
31 | return ObjCDeveloper()
32 | }
33 | }
34 |
35 | struct SwiftDeveloperFactory: DeveloperFactory {
36 | func newDeveloper() -> Developer {
37 | return SwiftDeveloper()
38 | }
39 | }
40 |
41 | enum Languages {
42 | case objC
43 | case swift
44 |
45 | var factory: DeveloperFactory {
46 | switch self {
47 | case .objC:
48 | return ObjCDeveloperFactory()
49 | case .swift:
50 | return SwiftDeveloperFactory()
51 | }
52 | }
53 | }
54 | /*:
55 | ### Usage
56 | */
57 | let developer = Languages.swift.factory.newDeveloper()
58 | developer.writeCode()
59 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Proxy.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | ☔ Proxy
13 | ------------------
14 |
15 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
16 |
17 | ### Example
18 | */
19 | protocol Project {
20 | func run()
21 | }
22 |
23 | struct RealProject: Project {
24 | var url: String
25 |
26 | func load() {
27 | print("Loading project from url \(url) ...")
28 | }
29 |
30 | init(url: String) {
31 | self.url = url
32 | load()
33 | }
34 |
35 | func run() {
36 | print("Running project \(url) ...")
37 | }
38 | }
39 |
40 | class ProxyProject: Project {
41 | var url: String
42 | var realProject: RealProject?
43 |
44 | func run() {
45 | if realProject == nil {
46 | realProject = RealProject(url: url)
47 | }
48 | realProject!.run()
49 | }
50 |
51 | init(url: String) {
52 | self.url = url
53 | }
54 | }
55 | /*:
56 | ### Usage
57 | */
58 | var project = ProxyProject(url: "https://github.com/zsergey/realProject")
59 | project.run()
60 |
--------------------------------------------------------------------------------
/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 | protocol Developer {
10 | func writeCode()
11 | }
12 |
13 | protocol Team {
14 | var developers: [Developer] { set get }
15 | func addDeveloper(developer: Developer)
16 | func createProject()
17 | }
18 |
19 | struct SwiftDeveloper: Developer{
20 | func writeCode() {
21 | print("Swift Developer writes Swift code...")
22 | }
23 | }
24 |
25 | struct ObjCDeveloper: Developer{
26 | func writeCode() {
27 | print("ObjC Developer writes Objective-C code...")
28 | }
29 | }
30 |
31 | class BankTeam: Team {
32 | var developers = [Developer]()
33 |
34 | func addDeveloper(developer: Developer) {
35 | developers.append(developer)
36 | }
37 |
38 | func createProject() {
39 | for developer in developers {
40 | developer.writeCode()
41 | }
42 | }
43 | }
44 | /*:
45 | ### Usage:
46 | */
47 | let team = BankTeam()
48 | team.addDeveloper(developer: ObjCDeveloper())
49 | team.addDeveloper(developer: ObjCDeveloper())
50 | team.addDeveloper(developer: ObjCDeveloper())
51 | team.addDeveloper(developer: ObjCDeveloper())
52 | team.addDeveloper(developer: SwiftDeveloper())
53 | team.createProject()
54 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Template-method.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🐾 Template Method
13 | ----------
14 |
15 | The template method pattern is used to define the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.
16 |
17 | ### Example
18 | */
19 | protocol WebsiteTemplate {
20 | func showPageContent()
21 | }
22 |
23 | extension WebsiteTemplate {
24 | func showPage() {
25 | print("Header")
26 | showPageContent()
27 | print("Footer")
28 | }
29 | }
30 |
31 | struct WelcomePage: WebsiteTemplate {
32 | func showPageContent() {
33 | print("Welcome")
34 | }
35 | }
36 |
37 | struct NewsPage: WebsiteTemplate {
38 | func showPageContent() {
39 | print("News")
40 | }
41 | }
42 | /*:
43 | ### Usage
44 | */
45 | let welcomePage = WelcomePage()
46 | welcomePage.showPage()
47 | print("")
48 |
49 | let newsPage = NewsPage()
50 | newsPage.showPage()
51 |
--------------------------------------------------------------------------------
/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 | struct Project {
10 | var version: String
11 | var code: String
12 |
13 | func save() -> Save {
14 | return Save(version: version, code: code)
15 | }
16 |
17 | mutating func load(save: Save) {
18 | version = save.version
19 | code = save.code
20 | }
21 |
22 | func description() -> String {
23 | return "Project version = \(version): \n'\(code)'\n"
24 | }
25 | }
26 |
27 | struct Save {
28 | var version: String
29 | var code: String
30 | }
31 |
32 | struct GithubRepo {
33 | var save: Save
34 | }
35 | /*:
36 | ### Usage
37 | */
38 | print("Creating new project. Version 1.0")
39 | var project = Project(version: "1.0", code: "let index = 0")
40 | print(project.description())
41 |
42 | print("Saving current version to github")
43 | let github = GithubRepo(save: project.save())
44 |
45 | print("Updating project to Version 1.1")
46 | print("Writing poor code...")
47 | print("Set version 1.1")
48 | project.version = "1.1"
49 | project.code = "let index = 0\nindex = 5"
50 | print(project.description())
51 |
52 | print("Something went wrong")
53 | print("Rolling back to Version 1.0")
54 |
55 | project.load(save: github.save)
56 | print("Project after rollback")
57 | print(project.description())
58 |
--------------------------------------------------------------------------------
/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 Database {
10 | func insert()
11 | func update()
12 | func select()
13 | func remove()
14 | }
15 |
16 | class SwiftApp {
17 | func saveObject() {
18 | print("Saving Swift Object...")
19 | }
20 |
21 | func updateObject() {
22 | print("Updating Swift Object...")
23 | }
24 |
25 | func loadObject() {
26 | print("Loading Swift Object...")
27 | }
28 |
29 | func deleteObject() {
30 | print("Deleting Swift Object...")
31 | }
32 | }
33 |
34 | class AdapterSwiftAppToDatabase: SwiftApp, Database {
35 | func insert() {
36 | saveObject()
37 | }
38 |
39 | func update() {
40 | updateObject()
41 | }
42 |
43 | func select() {
44 | loadObject()
45 | }
46 |
47 | func remove() {
48 | deleteObject()
49 | }
50 | }
51 |
52 | struct DatabaseManager {
53 | var database: Database
54 | func run() {
55 | database.insert()
56 | database.update()
57 | database.select()
58 | database.remove()
59 | }
60 | }
61 | /*:
62 | ### Usage
63 | */
64 | let databaseManager = DatabaseManager(database: AdapterSwiftAppToDatabase())
65 | databaseManager.run()
66 | /*:
67 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Adapter)
68 | */
69 |
--------------------------------------------------------------------------------
/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 | protocol Activity {
11 | func justDoIt()
12 | }
13 |
14 | struct Coding: Activity {
15 | func justDoIt() {
16 | print("Writing code...")
17 | }
18 | }
19 |
20 | struct Reading: Activity {
21 | func justDoIt() {
22 | print("Reading book...")
23 | }
24 | }
25 |
26 | struct Sleeping: Activity {
27 | func justDoIt() {
28 | print("Sleeping...")
29 | }
30 | }
31 |
32 | struct Training: Activity {
33 | func justDoIt() {
34 | print("Training...")
35 | }
36 | }
37 |
38 | struct Developer {
39 | var activity: Activity
40 |
41 | mutating func changeActivity() {
42 | if let _ = activity as? Sleeping {
43 | activity = Training()
44 | } else if let _ = activity as? Training {
45 | activity = Coding()
46 | } else if let _ = activity as? Coding {
47 | activity = Reading()
48 | } else if let _ = activity as? Reading {
49 | activity = Sleeping()
50 | }
51 | }
52 |
53 | func justDoIt() {
54 | activity.justDoIt()
55 | }
56 | }
57 | /*:
58 | ### Usage
59 | */
60 | let activity = Sleeping()
61 | var developer = Developer(activity: activity)
62 | for i in 0..<10 {
63 | developer.justDoIt()
64 | developer.changeActivity()
65 | }
66 | /*:
67 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State)
68 | */
69 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Facade.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🎁 Façade
13 | ---------
14 |
15 | The facade pattern is used to define a simplified interface to a more complex subsystem.
16 |
17 | ### Example
18 | */
19 | class Job {
20 | func doJob() {
21 | print("Job is progress...")
22 | }
23 | }
24 |
25 | class BugTracker {
26 | var isActiveSprint = false
27 |
28 | func startSprint() {
29 | print("Sprint is active")
30 | isActiveSprint = true
31 | }
32 |
33 | func stopSprint() {
34 | print("Sprint is not active")
35 | isActiveSprint = false
36 | }
37 | }
38 |
39 | class Developer {
40 | func doJobBeforeDeadline(bugTracker: BugTracker) {
41 | if bugTracker.isActiveSprint {
42 | print("Developer is solving problems...")
43 | } else {
44 | print("Developer is reading the news...")
45 | }
46 | }
47 | }
48 |
49 | class Workflow {
50 | let developer = Developer()
51 | let job = Job()
52 | let bugTracker = BugTracker()
53 | func solveProblems() {
54 | job.doJob()
55 | bugTracker.startSprint()
56 | developer.doJobBeforeDeadline(bugTracker: bugTracker)
57 | }
58 | }
59 | /*:
60 | ### Usage
61 | */
62 | let workflow = Workflow()
63 | workflow.solveProblems()
64 |
--------------------------------------------------------------------------------
/Creational.playground/Pages/Prototype.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🃏 Prototype
13 | ------------
14 |
15 | The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
16 | This practise is particularly useful when the construction of a new object is inefficient.
17 |
18 | ### Example
19 | */
20 | protocol Copyable {
21 | func copy() -> Any
22 | }
23 |
24 | struct Project: Copyable {
25 | var id: Int
26 | var name: String
27 | var source: String
28 |
29 | func copy() -> Any {
30 | let object = Project(id: id, name: name, source: source)
31 | return object
32 | }
33 | }
34 |
35 | struct ProjectFactory {
36 | var project: Project
37 | func cloneProject() -> Project {
38 | return project.copy() as! Project
39 | }
40 | }
41 | /*:
42 | ### Usage
43 | */
44 | let master = Project(id: 1, name: "Playground.swift", source: "let sourceCode = SourceCode()")
45 | let factory = ProjectFactory(project: master)
46 | let masterClone = factory.cloneProject()
47 | /*:
48 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Prototype)
49 | */
50 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Decorator.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🍧 Decorator
13 | ------------
14 |
15 | 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.
16 | This provides a flexible alternative to using inheritance to modify behaviour.
17 |
18 | ### Example
19 | */
20 | protocol Developer {
21 | func makeJob() -> String
22 | }
23 |
24 | struct SwiftDeveloper: Developer {
25 | func makeJob() -> String {
26 | return "Write Swift code"
27 | }
28 | }
29 |
30 | class DeveloperDecorator: Developer {
31 | var developer: Developer
32 | func makeJob() -> String {
33 | return developer.makeJob()
34 | }
35 | init(developer: Developer) {
36 | self.developer = developer
37 | }
38 | }
39 |
40 | class SeniorSwiftDeveloper: DeveloperDecorator {
41 | let codeReview = "Make code review"
42 | override func makeJob() -> String {
43 | return super.makeJob() + " & " + codeReview
44 | }
45 | }
46 |
47 | class SwiftTeamLead: DeveloperDecorator {
48 | let sendWeekReport = "Send week report"
49 | override func makeJob() -> String {
50 | return super.makeJob() + " & " + sendWeekReport
51 | }
52 | }
53 | /*:
54 | ### Usage:
55 | */
56 | let developer = SwiftTeamLead(developer: SeniorSwiftDeveloper(developer: SwiftDeveloper()))
57 | print(developer.makeJob())
58 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Bridge.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🌉 Bridge
13 | ----------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Developer {
20 | func writeCode()
21 | }
22 |
23 | protocol Program {
24 | var developer: Developer { get set }
25 | func develop()
26 | }
27 |
28 | struct SwiftDeveloper: Developer {
29 | func writeCode() {
30 | print("Swift Developer writes Swift code...")
31 | }
32 | }
33 |
34 | struct ObjCDeveloper: Developer {
35 | func writeCode() {
36 | print("ObjC Developer writes Objective-C code...")
37 | }
38 | }
39 |
40 | struct BankSystem: Program {
41 | var developer: Developer
42 |
43 | func develop() {
44 | print("Bank System development in progress...")
45 | developer.writeCode()
46 | }
47 | }
48 |
49 | struct StockExchange: Program {
50 | var developer: Developer
51 |
52 | func develop() {
53 | print("Stock Exchange development in progress...")
54 | developer.writeCode()
55 | }
56 | }
57 | /*:
58 | ### Usage
59 | */
60 | let programs: [Program] = [BankSystem(developer: ObjCDeveloper()),
61 | StockExchange(developer: SwiftDeveloper())]
62 | for program in programs {
63 | program.develop()
64 | }
65 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/playground.xcworkspace/xcshareddata/Design-Patterns.xccheckout:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDESourceControlProjectFavoriteDictionaryKey
6 |
7 | IDESourceControlProjectIdentifier
8 | 6E6A675F-9997-43AE-BB1C-8E4B69F9AD36
9 | IDESourceControlProjectName
10 | Design-Patterns
11 | IDESourceControlProjectOriginsDictionary
12 |
13 | C96876E4909DB6FA99FAEC5AD77808104236AA02
14 | https://github.com/ochococo/Design-Patterns-In-Swift.git
15 |
16 | IDESourceControlProjectPath
17 | Design-Patterns.playground
18 | IDESourceControlProjectRelativeInstallPathDictionary
19 |
20 | C96876E4909DB6FA99FAEC5AD77808104236AA02
21 | ..
22 |
23 | IDESourceControlProjectURL
24 | https://github.com/ochococo/Design-Patterns-In-Swift.git
25 | IDESourceControlProjectVersion
26 | 111
27 | IDESourceControlProjectWCCIdentifier
28 | C96876E4909DB6FA99FAEC5AD77808104236AA02
29 | IDESourceControlProjectWCConfigurations
30 |
31 |
32 | IDESourceControlRepositoryExtensionIdentifierKey
33 | public.vcs.git
34 | IDESourceControlWCCIdentifierKey
35 | C96876E4909DB6FA99FAEC5AD77808104236AA02
36 | IDESourceControlWCCName
37 | Design-Patterns-In-Swift
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Composite.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🌿 Composite
13 | -------------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Developer {
20 | func writeCode()
21 | }
22 |
23 | protocol Team {
24 | var developers: [Developer] { set get }
25 | func addDeveloper(developer: Developer)
26 | func createProject()
27 | }
28 |
29 | struct SwiftDeveloper: Developer{
30 | func writeCode() {
31 | print("Swift Developer writes Swift code...")
32 | }
33 | }
34 |
35 | struct ObjCDeveloper: Developer{
36 | func writeCode() {
37 | print("ObjC Developer writes Objective-C code...")
38 | }
39 | }
40 |
41 | class BankTeam: Team {
42 | var developers = [Developer]()
43 |
44 | func addDeveloper(developer: Developer) {
45 | developers.append(developer)
46 | }
47 |
48 | func createProject() {
49 | for developer in developers {
50 | developer.writeCode()
51 | }
52 | }
53 | }
54 | /*:
55 | ### Usage:
56 | */
57 | let team = BankTeam()
58 | team.addDeveloper(developer: ObjCDeveloper())
59 | team.addDeveloper(developer: ObjCDeveloper())
60 | team.addDeveloper(developer: ObjCDeveloper())
61 | team.addDeveloper(developer: ObjCDeveloper())
62 | team.addDeveloper(developer: SwiftDeveloper())
63 | team.createProject()
64 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Iterator.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🍫 Iterator
13 | -----------
14 |
15 | 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.
16 |
17 | ### Example:
18 | */
19 | protocol Iterator {
20 | func hasNext() -> Bool
21 | mutating func next() -> String
22 | }
23 |
24 | protocol Collection {
25 | func getIterator() -> Iterator
26 | }
27 |
28 | struct SwiftDeveloper: Collection {
29 | var name: String
30 | var skills: [String]
31 |
32 | private struct SkillIterator: Iterator {
33 | var index: Int
34 | var data: [String]
35 | func hasNext() -> Bool {
36 | return index < data.count
37 | }
38 | mutating func next() -> String {
39 | let result = data[index]
40 | index = index + 1
41 | return result
42 | }
43 | }
44 |
45 | func getIterator() -> Iterator {
46 | return SkillIterator(index: 0, data: skills)
47 | }
48 | }
49 | /*:
50 | ### Usage
51 | */
52 | let skills = ["Swift", "ObjC", "Sketch", "PM"]
53 | let swiftDeveloper = SwiftDeveloper(name: "Sergey Zapuhlyak", skills: skills)
54 | var iterator = swiftDeveloper.getIterator()
55 | print("Developer \(swiftDeveloper.name)")
56 | print("Skills")
57 | while iterator.hasNext() {
58 | print("\(iterator.next())")
59 | }
60 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Strategy.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 💡 Strategy
13 | -----------
14 |
15 | The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
16 |
17 | ### Example
18 | */
19 | protocol Activity {
20 | func justDoIt()
21 | }
22 |
23 | struct Coding: Activity {
24 | func justDoIt() {
25 | print("Writing code...")
26 | }
27 | }
28 |
29 | struct Reading: Activity {
30 | func justDoIt() {
31 | print("Reading book...")
32 | }
33 | }
34 |
35 | struct Sleeping: Activity {
36 | func justDoIt() {
37 | print("Sleeping...")
38 | }
39 | }
40 |
41 | struct Training: Activity {
42 | func justDoIt() {
43 | print("Training...")
44 | }
45 | }
46 |
47 | struct Developer {
48 | var activity: Activity
49 |
50 | func executeActivity() {
51 | activity.justDoIt()
52 | }
53 | }
54 | /*:
55 | ### Usage
56 | */
57 | var developer = Developer(activity: Sleeping())
58 | developer.executeActivity()
59 |
60 | developer.activity = Training()
61 | developer.executeActivity()
62 |
63 | developer.activity = Coding()
64 | developer.executeActivity()
65 |
66 | developer.activity = Reading()
67 | developer.executeActivity()
68 |
69 | developer.activity = Sleeping()
70 | developer.executeActivity()
71 | /*:
72 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy)
73 | */
74 |
--------------------------------------------------------------------------------
/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 | protocol Developer {
7 | func writeCode()
8 | }
9 |
10 | struct SwiftDeveloper: Developer {
11 | func writeCode() {
12 | print("Swift Developer writes Swift code...")
13 | }
14 | }
15 |
16 | struct ObjCDeveloper: Developer {
17 | func writeCode() {
18 | print("ObjC Developer writes Objective-C code...")
19 | }
20 | }
21 |
22 | enum Languages: String {
23 | case Swift
24 | case ObjC
25 |
26 | var description: String {
27 | return self.rawValue
28 | }
29 | }
30 |
31 | struct DeveloperFactory {
32 | private var developers = [String: Developer]()
33 |
34 | mutating func developer(by language: Languages) -> Developer {
35 | if let value = developers[language.description] {
36 | return value
37 | } else {
38 | var value: Developer? = nil
39 | print("Hiring \(language.description) developer ")
40 | switch language {
41 | case .Swift:
42 | value = SwiftDeveloper()
43 | case .ObjC:
44 | value = ObjCDeveloper()
45 | }
46 | developers[language.description] = value
47 | return value!
48 | }
49 | }
50 | }
51 | /*:
52 | ### Usage
53 | */
54 | var developerFactory = DeveloperFactory()
55 | var developers = [Developer]()
56 | developers.append(developerFactory.developer(by: .Swift))
57 | developers.append(developerFactory.developer(by: .Swift))
58 | developers.append(developerFactory.developer(by: .Swift))
59 | developers.append(developerFactory.developer(by: .ObjC))
60 | developers.append(developerFactory.developer(by: .ObjC))
61 | developers.append(developerFactory.developer(by: .ObjC))
62 | for developer in developers {
63 | developer.writeCode()
64 | }
65 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Adapter.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🔌 Adapter
13 | ----------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Database {
20 | func insert()
21 | func update()
22 | func select()
23 | func remove()
24 | }
25 |
26 | class SwiftApp {
27 | func saveObject() {
28 | print("Saving Swift Object...")
29 | }
30 |
31 | func updateObject() {
32 | print("Updating Swift Object...")
33 | }
34 |
35 | func loadObject() {
36 | print("Loading Swift Object...")
37 | }
38 |
39 | func deleteObject() {
40 | print("Deleting Swift Object...")
41 | }
42 | }
43 |
44 | class AdapterSwiftAppToDatabase: SwiftApp, Database {
45 | func insert() {
46 | saveObject()
47 | }
48 |
49 | func update() {
50 | updateObject()
51 | }
52 |
53 | func select() {
54 | loadObject()
55 | }
56 |
57 | func remove() {
58 | deleteObject()
59 | }
60 | }
61 |
62 | struct DatabaseManager {
63 | var database: Database
64 | func run() {
65 | database.insert()
66 | database.update()
67 | database.select()
68 | database.remove()
69 | }
70 | }
71 | /*:
72 | ### Usage
73 | */
74 | let databaseManager = DatabaseManager(database: AdapterSwiftAppToDatabase())
75 | databaseManager.run()
76 | /*:
77 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Adapter)
78 | */
79 |
--------------------------------------------------------------------------------
/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 | protocol Expression {
10 | func interpret(_ context: String) -> Bool
11 | }
12 |
13 | struct AndExpression: Expression {
14 | var expression1: Expression
15 | var expression2: Expression
16 |
17 | func interpret(_ context: String) -> Bool {
18 | return expression1.interpret(context) && expression2.interpret(context)
19 | }
20 | }
21 |
22 | struct OrExpression: Expression {
23 | var expression1: Expression
24 | var expression2: Expression
25 |
26 | func interpret(_ context: String) -> Bool {
27 | return expression1.interpret(context) || expression2.interpret(context)
28 | }
29 | }
30 |
31 | struct TerminalExpression: Expression {
32 | var data: String
33 |
34 | func interpret(_ context: String) -> Bool {
35 | return context.contains(data)
36 | }
37 | }
38 | /*:
39 | ### Usage
40 | */
41 | struct Interpreter {
42 | static func getAppleExpression() -> Expression {
43 | let swift = TerminalExpression(data: "Swift")
44 | let objC = TerminalExpression(data: "Objective-C")
45 | return OrExpression(expression1: objC, expression2: swift)
46 | }
47 |
48 | static func getJavaEEExpression() -> Expression {
49 | let java = TerminalExpression(data: "Java")
50 | let spring = TerminalExpression(data: "Spring")
51 | return AndExpression(expression1: java, expression2: spring)
52 | }
53 | }
54 |
55 | let appleExpression = Interpreter.getAppleExpression()
56 | let javaExpression = Interpreter.getJavaEEExpression()
57 | print("Is Developer an Apple Developer \(appleExpression.interpret("Swift"))")
58 | print("Does developer knows Java EE \(javaExpression.interpret("Java Spring"))")
59 | /*:
60 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter)
61 | */
62 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Memento.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 💾 Memento
13 | ----------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | struct Project {
20 | var version: String
21 | var code: String
22 |
23 | func save() -> Save {
24 | return Save(version: version, code: code)
25 | }
26 |
27 | mutating func load(save: Save) {
28 | version = save.version
29 | code = save.code
30 | }
31 |
32 | func description() -> String {
33 | return "Project version = \(version): \n'\(code)'\n"
34 | }
35 | }
36 |
37 | struct Save {
38 | var version: String
39 | var code: String
40 | }
41 |
42 | struct GithubRepo {
43 | var save: Save
44 | }
45 | /*:
46 | ### Usage
47 | */
48 | print("Creating new project. Version 1.0")
49 | var project = Project(version: "1.0", code: "let index = 0")
50 | print(project.description())
51 |
52 | print("Saving current version to github")
53 | let github = GithubRepo(save: project.save())
54 |
55 | print("Updating project to Version 1.1")
56 | print("Writing poor code...")
57 | print("Set version 1.1")
58 | project.version = "1.1"
59 | project.code = "let index = 0\nindex = 5"
60 | print(project.description())
61 |
62 | print("Something went wrong")
63 | print("Rolling back to Version 1.0")
64 |
65 | project.load(save: github.save)
66 | print("Project after rollback")
67 | print(project.description())
68 |
--------------------------------------------------------------------------------
/Creational.playground/Pages/Factory.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🏭 Factory Method
13 | -----------------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Developer {
20 | func writeCode()
21 | }
22 |
23 | struct ObjCDeveloper: Developer {
24 | func writeCode() {
25 | print("ObjC developer writes Objective C code...")
26 | }
27 | }
28 |
29 | struct SwiftDeveloper: Developer {
30 | func writeCode() {
31 | print("Swift developer writes Swift code...")
32 | }
33 | }
34 |
35 | protocol DeveloperFactory {
36 | func newDeveloper() -> Developer
37 | }
38 |
39 | struct ObjCDeveloperFactory: DeveloperFactory {
40 | func newDeveloper() -> Developer {
41 | return ObjCDeveloper()
42 | }
43 | }
44 |
45 | struct SwiftDeveloperFactory: DeveloperFactory {
46 | func newDeveloper() -> Developer {
47 | return SwiftDeveloper()
48 | }
49 | }
50 |
51 | enum Languages {
52 | case objC
53 | case swift
54 |
55 | var factory: DeveloperFactory {
56 | switch self {
57 | case .objC:
58 | return ObjCDeveloperFactory()
59 | case .swift:
60 | return SwiftDeveloperFactory()
61 | }
62 | }
63 | }
64 | /*:
65 | ### Usage
66 | */
67 | let developer = Languages.swift.factory.newDeveloper()
68 | developer.writeCode()
69 |
--------------------------------------------------------------------------------
/generate-playground.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | cleanThisMessForReadme () {
4 |
5 | FILENAME=$1
6 |
7 | { rm $FILENAME && awk '{gsub("\\*/", "\n```swift\n", $0); print}' > $FILENAME; } < $FILENAME
8 | { rm $FILENAME && awk '{gsub("\\*//\\*:", "", $0); print}' > $FILENAME; } < $FILENAME
9 | { rm $FILENAME && awk '{gsub("/\\*:", "```\n", $0); print}' > $FILENAME; } < $FILENAME
10 | { rm $FILENAME && awk '{gsub("//\\*:", "", $0); print}' > $FILENAME; } < $FILENAME
11 | { rm $FILENAME && awk '{gsub("//:", "", $0); print}' > $FILENAME; } < $FILENAME
12 | { rm $FILENAME && awk 'NR>1{print buf}{buf = $0}' > $FILENAME; } < $FILENAME
13 | }
14 |
15 | makePlayground () {
16 | for i in $( ls source/$1 );
17 | do
18 |
19 | if [[ $i == *"title"* ]]; then
20 | continue
21 | fi
22 |
23 | cat source/$1/_title.swift source/$1/$i > $i
24 | baseName=`echo $i | cut -d "." -f 1`
25 |
26 | cp $i ./$1.playground/Pages/$baseName.xcplaygroundpage/Contents.swift
27 | rm $i
28 |
29 | done
30 | }
31 |
32 | cat source/behavioral/* > ./Behavioral.swift
33 | cat source/creational/* > ./Creational.swift
34 | cat source/structural/* > ./Structural.swift
35 |
36 | cp ./Behavioral.swift ./Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
37 | cp ./Creational.swift ./Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift
38 | cp ./Structural.swift ./Design-Patterns.playground/Pages/Structural.xcplaygroundpage/Contents.swift
39 |
40 | cat source/header.swift source/*/* source/footer.swift > ./contents.swift
41 |
42 | cleanThisMessForReadme ./contents.swift
43 |
44 | cp ./contents.swift ./README.md
45 |
46 | #zip -r -X Design-Patterns.playground.zip ./Design-Patterns.playground
47 |
48 | rm ./Behavioral.swift
49 | rm ./Creational.swift
50 | rm ./Structural.swift
51 | rm ./contents.swift
52 |
53 | makePlayground Behavioral
54 | makePlayground Creational
55 | makePlayground Structural
56 |
57 | zip -r -X Design-Patterns.zip ./Behavioral.playground ./Creational.playground ./Structural.playground
58 |
59 |
60 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/State.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🐉 State
13 | ---------
14 |
15 | The state pattern is used to alter the behaviour of an object as its internal state changes.
16 | The pattern allows the class for an object to apparently change at run-time.
17 |
18 | ### Example
19 | */
20 | protocol Activity {
21 | func justDoIt()
22 | }
23 |
24 | struct Coding: Activity {
25 | func justDoIt() {
26 | print("Writing code...")
27 | }
28 | }
29 |
30 | struct Reading: Activity {
31 | func justDoIt() {
32 | print("Reading book...")
33 | }
34 | }
35 |
36 | struct Sleeping: Activity {
37 | func justDoIt() {
38 | print("Sleeping...")
39 | }
40 | }
41 |
42 | struct Training: Activity {
43 | func justDoIt() {
44 | print("Training...")
45 | }
46 | }
47 |
48 | struct Developer {
49 | var activity: Activity
50 |
51 | mutating func changeActivity() {
52 | if let _ = activity as? Sleeping {
53 | activity = Training()
54 | } else if let _ = activity as? Training {
55 | activity = Coding()
56 | } else if let _ = activity as? Coding {
57 | activity = Reading()
58 | } else if let _ = activity as? Reading {
59 | activity = Sleeping()
60 | }
61 | }
62 |
63 | func justDoIt() {
64 | activity.justDoIt()
65 | }
66 | }
67 | /*:
68 | ### Usage
69 | */
70 | let activity = Sleeping()
71 | var developer = Developer(activity: activity)
72 | for i in 0..<10 {
73 | developer.justDoIt()
74 | developer.changeActivity()
75 | }
76 | /*:
77 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State)
78 | */
79 |
--------------------------------------------------------------------------------
/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 | struct Database {
10 | func insert() {
11 | print("Inserting record...")
12 | }
13 |
14 | func update() {
15 | print("Updating record...")
16 | }
17 |
18 | func select() {
19 | print("Reading record...")
20 | }
21 |
22 | func delete() {
23 | print("Deleting record...")
24 | }
25 | }
26 |
27 | protocol Command {
28 | var database: Database { set get }
29 | func execute()
30 | }
31 |
32 | struct InsertCommand: Command {
33 | internal var database: Database
34 |
35 | func execute() {
36 | database.insert()
37 | }
38 | }
39 |
40 | struct UpdateCommand: Command {
41 | internal var database: Database
42 |
43 | func execute() {
44 | database.update()
45 | }
46 | }
47 |
48 | struct SelectCommand: Command {
49 | internal var database: Database
50 |
51 | func execute() {
52 | database.select()
53 | }
54 | }
55 |
56 | struct DeleteCommand: Command {
57 | internal var database: Database
58 |
59 | func execute() {
60 | database.delete()
61 | }
62 | }
63 |
64 | struct Developer {
65 | var insert, update, select, delete: Command
66 |
67 | func insertRecord() {
68 | insert.execute()
69 | }
70 |
71 | func updateRecord() {
72 | update.execute()
73 | }
74 |
75 | func selectRecord() {
76 | select.execute()
77 | }
78 |
79 | func deleteRecord() {
80 | delete.execute()
81 | }
82 | }
83 | /*:
84 | ### Usage:
85 | */
86 | let database = Database()
87 | let insertCommand = InsertCommand(database: database)
88 | let updateCommand = UpdateCommand(database: database)
89 | let selectCommand = SelectCommand(database: database)
90 | let deleteCommand = DeleteCommand(database: database)
91 |
92 | let developer = Developer(insert: insertCommand, update: updateCommand, select: selectCommand, delete: deleteCommand)
93 | developer.insertRecord()
94 | developer.updateRecord()
95 | developer.selectRecord()
96 | developer.deleteRecord()
97 |
--------------------------------------------------------------------------------
/Structural.playground/Pages/Flyweight.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | ## 🍃 Flyweight
13 | The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
14 | ### Example
15 | */
16 | protocol Developer {
17 | func writeCode()
18 | }
19 |
20 | struct SwiftDeveloper: Developer {
21 | func writeCode() {
22 | print("Swift Developer writes Swift code...")
23 | }
24 | }
25 |
26 | struct ObjCDeveloper: Developer {
27 | func writeCode() {
28 | print("ObjC Developer writes Objective-C code...")
29 | }
30 | }
31 |
32 | enum Languages: String {
33 | case Swift
34 | case ObjC
35 |
36 | var description: String {
37 | return self.rawValue
38 | }
39 | }
40 |
41 | struct DeveloperFactory {
42 | private var developers = [String: Developer]()
43 |
44 | mutating func developer(by language: Languages) -> Developer {
45 | if let value = developers[language.description] {
46 | return value
47 | } else {
48 | var value: Developer? = nil
49 | print("Hiring \(language.description) developer ")
50 | switch language {
51 | case .Swift:
52 | value = SwiftDeveloper()
53 | case .ObjC:
54 | value = ObjCDeveloper()
55 | }
56 | developers[language.description] = value
57 | return value!
58 | }
59 | }
60 | }
61 | /*:
62 | ### Usage
63 | */
64 | var developerFactory = DeveloperFactory()
65 | var developers = [Developer]()
66 | developers.append(developerFactory.developer(by: .Swift))
67 | developers.append(developerFactory.developer(by: .Swift))
68 | developers.append(developerFactory.developer(by: .Swift))
69 | developers.append(developerFactory.developer(by: .ObjC))
70 | developers.append(developerFactory.developer(by: .ObjC))
71 | developers.append(developerFactory.developer(by: .ObjC))
72 | for developer in developers {
73 | developer.writeCode()
74 | }
75 |
--------------------------------------------------------------------------------
/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 | protocol Notifier {
10 | var priority: Int { set get }
11 | var nextNotifier: Notifier? { set get }
12 | func write(_ message: String)
13 | }
14 |
15 | extension Notifier {
16 | func notifyManager(message: String, level: Int) {
17 | if level >= priority {
18 | write(message)
19 | }
20 | if let nextNotifie = self.nextNotifier {
21 | nextNotifie.notifyManager(message: message, level: level)
22 | }
23 | }
24 | }
25 |
26 | enum Priority {
27 | case routine
28 | case important
29 | case asSoonAsPossible
30 | }
31 |
32 | struct SimpleReportNotifier: Notifier {
33 | internal var nextNotifier: Notifier?
34 | internal var priority: Int
35 |
36 | func write(_ message: String) {
37 | print("Notifying using simple report: \(message)")
38 | }
39 | }
40 |
41 | struct EmailNotifier: Notifier {
42 | internal var nextNotifier: Notifier?
43 | internal var priority: Int
44 |
45 | func write(_ message: String) {
46 | print("Sending email: \(message)")
47 | }
48 | }
49 |
50 | struct SMSNotifier: Notifier {
51 | internal var nextNotifier: Notifier?
52 | internal var priority: Int
53 |
54 | func write(_ message: String) {
55 | print("Sending sms to manager: \(message)")
56 | }
57 | }
58 | /*:
59 | ### Usage
60 | */
61 | let smsNotifier = SMSNotifier(nextNotifier: nil, priority: Priority.asSoonAsPossible.hashValue)
62 | let emailNotifier = EmailNotifier(nextNotifier: smsNotifier, priority: Priority.important.hashValue)
63 | let reportNotifier = SimpleReportNotifier(nextNotifier: emailNotifier, priority: Priority.routine.hashValue)
64 |
65 | reportNotifier.notifyManager(message: "Everything is OK", level: Priority.routine.hashValue)
66 | reportNotifier.notifyManager(message: "Something went wrong", level: Priority.important.hashValue)
67 | reportNotifier.notifyManager(message: "Houston, we've had a problem here!", level: Priority.asSoonAsPossible.hashValue)
68 | /*:
69 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility)
70 | */
71 |
--------------------------------------------------------------------------------
/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 Developer {
10 | func create(project: ProjectClass)
11 | func create(project: Database)
12 | func create(project: Test)
13 | }
14 |
15 | protocol ProjectElement {
16 | func beWritten(developer: Developer)
17 | }
18 |
19 | struct ProjectClass: ProjectElement {
20 | func beWritten(developer: Developer) {
21 | developer.create(project: self)
22 | }
23 | }
24 |
25 | struct Database: ProjectElement {
26 | func beWritten(developer: Developer) {
27 | developer.create(project: self)
28 | }
29 | }
30 |
31 | struct Test: ProjectElement {
32 | func beWritten(developer: Developer) {
33 | developer.create(project: self)
34 | }
35 | }
36 |
37 | struct Project: ProjectElement {
38 | var projectElements: [ProjectElement] = [ProjectClass(), Database(), Test()]
39 |
40 | func beWritten(developer: Developer) {
41 | for projectElement in projectElements {
42 | projectElement.beWritten(developer: developer)
43 | }
44 | }
45 | }
46 |
47 | struct JuniorDeveloper: Developer {
48 | func create(project: ProjectClass) {
49 | print("Writing poor class...")
50 | }
51 |
52 | func create(project: Database) {
53 | print("Drop database...")
54 | }
55 |
56 | func create(project: Test) {
57 | print("Creating not reliable test...")
58 | }
59 | }
60 |
61 | struct SeniorDeveloper: Developer {
62 | func create(project: ProjectClass) {
63 | print("Rewriting class after junior...")
64 | }
65 |
66 | func create(project: Database) {
67 | print("Fixing database...")
68 | }
69 |
70 | func create(project: Test) {
71 | print("Creating reliable test...")
72 | }
73 | }
74 | /*:
75 | ### Usage
76 | */
77 | let project = Project()
78 | let junior = JuniorDeveloper()
79 | let senior = SeniorDeveloper()
80 |
81 | print("Junior in Action")
82 | project.beWritten(developer: junior)
83 |
84 | print("")
85 |
86 | print("Senior in Action")
87 | project.beWritten(developer: senior)
88 | /*:
89 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor)
90 | */
91 |
--------------------------------------------------------------------------------
/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 | enum Cms {
11 | case wordpress
12 | case alifresco
13 | }
14 |
15 | struct Website {
16 | var name: String?
17 | var cms: Cms?
18 | var price: Int?
19 |
20 | func printWebsite(){
21 | guard let name = name, let cms = cms, let price = price else {
22 | return
23 | }
24 | print("Name \(name), cms \(cms), price \(price)")
25 | }
26 | }
27 |
28 | protocol WebsiteBuilder {
29 | var website: Website? { set get }
30 | func createWebsite()
31 | func buildName()
32 | func buildCms()
33 | func buildPrice()
34 | }
35 |
36 | class VisitCardWebsiteBuilder: WebsiteBuilder {
37 | internal var website: Website?
38 |
39 | internal func createWebsite() {
40 | self.website = Website()
41 | }
42 |
43 | internal func buildName() {
44 | self.website?.name = "Visit Card"
45 | }
46 |
47 | internal func buildCms() {
48 | self.website?.cms = .wordpress
49 | }
50 |
51 | internal func buildPrice() {
52 | self.website?.price = 500
53 | }
54 | }
55 |
56 | class EnterpriseWebsiteBuilder: WebsiteBuilder {
57 | internal var website: Website?
58 |
59 | internal func createWebsite() {
60 | self.website = Website()
61 | }
62 |
63 | internal func buildName() {
64 | self.website?.name = "Enterprise website"
65 | }
66 |
67 | internal func buildCms() {
68 | self.website?.cms = .alifresco
69 | }
70 |
71 | internal func buildPrice() {
72 | self.website?.price = 10000
73 | }
74 | }
75 |
76 | struct Director {
77 | var builder: WebsiteBuilder
78 |
79 | func buildWebsite() -> Website {
80 | builder.createWebsite()
81 | builder.buildName()
82 | builder.buildCms()
83 | builder.buildPrice()
84 | return builder.website!
85 | }
86 | }
87 | /*:
88 | ### Usage
89 | */
90 | let director = Director(builder: EnterpriseWebsiteBuilder())
91 | let website = director.buildWebsite()
92 | website.printWebsite()
93 | /*:
94 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Builder)
95 | */
96 |
--------------------------------------------------------------------------------
/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 Observer {
11 | var name: String { get }
12 |
13 | func handleEvent(vacancies: [String])
14 | }
15 |
16 | protocol Observed {
17 | mutating func addObserver(observer: Observer)
18 | mutating func removeObserver(observer: Observer)
19 | func notifyObservers()
20 | }
21 |
22 | struct Subscriber: Observer {
23 | var name: String
24 |
25 | func handleEvent(vacancies: [String]) {
26 | print("Dear \(name). We have some changes in vacancies:\n\(vacancies)\n")
27 | }
28 | }
29 |
30 | struct HeadHunter: Observed {
31 | var vacancies = [String]()
32 | var subscribers = [Observer]()
33 |
34 | mutating func addVacancy(vacancy: String) {
35 | vacancies.append(vacancy)
36 | notifyObservers()
37 | }
38 |
39 | mutating func removeVacancy(vacancy: String) {
40 | if let index = vacancies.index(of: vacancy) {
41 | vacancies.remove(at: index)
42 | notifyObservers()
43 | }
44 | }
45 |
46 | mutating func addObserver(observer: Observer) {
47 | subscribers.append(observer)
48 | }
49 |
50 | mutating func removeObserver(observer: Observer) {
51 | for index in 1...subscribers.count - 1 {
52 | let subscriber = subscribers[index]
53 | if subscriber.name == observer.name {
54 | subscribers.remove(at: index)
55 | break
56 | }
57 | }
58 | }
59 |
60 | func notifyObservers() {
61 | for subscriber in subscribers {
62 | subscriber.handleEvent(vacancies: vacancies)
63 | }
64 | }
65 | }
66 | /*:
67 | ### Usage
68 | */
69 | var hh = HeadHunter()
70 | hh.addVacancy(vacancy: "Swift Developer")
71 | hh.addVacancy(vacancy: "ObjC Developer")
72 |
73 | let zsergey = Subscriber(name: "Sergey Zapuhlyak")
74 | let azimin = Subscriber(name: "Alex Zimin")
75 |
76 | hh.addObserver(observer: zsergey)
77 | hh.addObserver(observer: azimin)
78 |
79 | hh.addVacancy(vacancy: "C++ Developer")
80 |
81 | hh.removeObserver(observer: azimin)
82 | hh.removeVacancy(vacancy: "ObjC Developer")
83 | /*:
84 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer)
85 | */
86 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Interpreter.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🎶 Interpreter
13 | --------------
14 |
15 | The interpreter pattern is used to evaluate sentences in a language.
16 |
17 | ### Example
18 | */
19 | protocol Expression {
20 | func interpret(_ context: String) -> Bool
21 | }
22 |
23 | struct AndExpression: Expression {
24 | var expression1: Expression
25 | var expression2: Expression
26 |
27 | func interpret(_ context: String) -> Bool {
28 | return expression1.interpret(context) && expression2.interpret(context)
29 | }
30 | }
31 |
32 | struct OrExpression: Expression {
33 | var expression1: Expression
34 | var expression2: Expression
35 |
36 | func interpret(_ context: String) -> Bool {
37 | return expression1.interpret(context) || expression2.interpret(context)
38 | }
39 | }
40 |
41 | struct TerminalExpression: Expression {
42 | var data: String
43 |
44 | func interpret(_ context: String) -> Bool {
45 | return context.contains(data)
46 | }
47 | }
48 | /*:
49 | ### Usage
50 | */
51 | struct Interpreter {
52 | static func getAppleExpression() -> Expression {
53 | let swift = TerminalExpression(data: "Swift")
54 | let objC = TerminalExpression(data: "Objective-C")
55 | return OrExpression(expression1: objC, expression2: swift)
56 | }
57 |
58 | static func getJavaEEExpression() -> Expression {
59 | let java = TerminalExpression(data: "Java")
60 | let spring = TerminalExpression(data: "Spring")
61 | return AndExpression(expression1: java, expression2: spring)
62 | }
63 | }
64 |
65 | let appleExpression = Interpreter.getAppleExpression()
66 | let javaExpression = Interpreter.getJavaEEExpression()
67 | print("Is Developer an Apple Developer \(appleExpression.interpret("Swift"))")
68 | print("Does developer knows Java EE \(javaExpression.interpret("Java Spring"))")
69 | /*:
70 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter)
71 | */
72 |
--------------------------------------------------------------------------------
/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 Chat {
10 | func sendMessage(_ message: String, from user: User)
11 | }
12 |
13 | protocol User {
14 | var ID: Int { set get }
15 | var name: String { set get }
16 | var chat: Chat { set get }
17 | func sendMessage(_ message: String)
18 | func getMessage(_ message: String)
19 | }
20 |
21 | struct Admin: User {
22 | internal var ID: Int
23 | internal var name: String
24 | internal var chat: Chat
25 |
26 | func sendMessage(_ message: String) {
27 | chat.sendMessage(message, from: self)
28 | }
29 |
30 | func getMessage(_ message: String) {
31 | print("\(name) received message: \(message)")
32 | }
33 | }
34 |
35 | struct Client: User {
36 | internal var ID: Int
37 | internal var name: String
38 | internal var chat: Chat
39 |
40 | func sendMessage(_ message: String) {
41 | chat.sendMessage(message, from: self)
42 | }
43 |
44 | func getMessage(_ message: String) {
45 | print("\(name) received message: \(message)")
46 | }
47 | }
48 |
49 | class Telegram: Chat {
50 | var admin: Admin?
51 | var clients: [Client]?
52 |
53 | func addClient(client: Client) {
54 | if clients == nil {
55 | clients = [Client]()
56 | }
57 | clients?.append(client)
58 | }
59 |
60 | func sendMessage(_ message: String, from user: User) {
61 | if let clients = clients {
62 | for client in clients {
63 | if client.ID != user.ID {
64 | client.getMessage(message)
65 | }
66 | }
67 | }
68 |
69 | admin?.getMessage(message)
70 | }
71 | }
72 | /*:
73 | ### Usage
74 | */
75 | var telegram = Telegram()
76 | let admin = Admin(ID: 1, name: "Pavel Durov", chat: telegram)
77 | let zsergey = Client(ID: 2, name: "Sergey Zapuhlyak", chat: telegram)
78 | let azimin = Client(ID: 3, name: "Alex Zimin", chat: telegram)
79 | telegram.admin = admin
80 | telegram.addClient(client: zsergey)
81 | telegram.addClient(client: azimin)
82 |
83 | zsergey.sendMessage("Hello, I am Sergey Zapuhlyak")
84 | admin.sendMessage("I am Administrator!")
85 | /*:
86 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator)
87 | */
88 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Chain-Of-Responsibility.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🐝 Chain Of Responsibility
13 | --------------------------
14 |
15 | The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
16 |
17 | ### Example:
18 | */
19 | protocol Notifier {
20 | var priority: Int { set get }
21 | var nextNotifier: Notifier? { set get }
22 | func write(_ message: String)
23 | }
24 |
25 | extension Notifier {
26 | func notifyManager(message: String, level: Int) {
27 | if level >= priority {
28 | write(message)
29 | }
30 | if let nextNotifie = self.nextNotifier {
31 | nextNotifie.notifyManager(message: message, level: level)
32 | }
33 | }
34 | }
35 |
36 | enum Priority {
37 | case routine
38 | case important
39 | case asSoonAsPossible
40 | }
41 |
42 | struct SimpleReportNotifier: Notifier {
43 | internal var nextNotifier: Notifier?
44 | internal var priority: Int
45 |
46 | func write(_ message: String) {
47 | print("Notifying using simple report: \(message)")
48 | }
49 | }
50 |
51 | struct EmailNotifier: Notifier {
52 | internal var nextNotifier: Notifier?
53 | internal var priority: Int
54 |
55 | func write(_ message: String) {
56 | print("Sending email: \(message)")
57 | }
58 | }
59 |
60 | struct SMSNotifier: Notifier {
61 | internal var nextNotifier: Notifier?
62 | internal var priority: Int
63 |
64 | func write(_ message: String) {
65 | print("Sending sms to manager: \(message)")
66 | }
67 | }
68 | /*:
69 | ### Usage
70 | */
71 | let smsNotifier = SMSNotifier(nextNotifier: nil, priority: Priority.asSoonAsPossible.hashValue)
72 | let emailNotifier = EmailNotifier(nextNotifier: smsNotifier, priority: Priority.important.hashValue)
73 | let reportNotifier = SimpleReportNotifier(nextNotifier: emailNotifier, priority: Priority.routine.hashValue)
74 |
75 | reportNotifier.notifyManager(message: "Everything is OK", level: Priority.routine.hashValue)
76 | reportNotifier.notifyManager(message: "Something went wrong", level: Priority.important.hashValue)
77 | reportNotifier.notifyManager(message: "Houston, we've had a problem here!", level: Priority.asSoonAsPossible.hashValue)
78 | /*:
79 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility)
80 | */
81 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Command.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 👫 Command
13 | ----------
14 |
15 | 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.
16 |
17 | ### Example:
18 | */
19 | struct Database {
20 | func insert() {
21 | print("Inserting record...")
22 | }
23 |
24 | func update() {
25 | print("Updating record...")
26 | }
27 |
28 | func select() {
29 | print("Reading record...")
30 | }
31 |
32 | func delete() {
33 | print("Deleting record...")
34 | }
35 | }
36 |
37 | protocol Command {
38 | var database: Database { set get }
39 | func execute()
40 | }
41 |
42 | struct InsertCommand: Command {
43 | internal var database: Database
44 |
45 | func execute() {
46 | database.insert()
47 | }
48 | }
49 |
50 | struct UpdateCommand: Command {
51 | internal var database: Database
52 |
53 | func execute() {
54 | database.update()
55 | }
56 | }
57 |
58 | struct SelectCommand: Command {
59 | internal var database: Database
60 |
61 | func execute() {
62 | database.select()
63 | }
64 | }
65 |
66 | struct DeleteCommand: Command {
67 | internal var database: Database
68 |
69 | func execute() {
70 | database.delete()
71 | }
72 | }
73 |
74 | struct Developer {
75 | var insert, update, select, delete: Command
76 |
77 | func insertRecord() {
78 | insert.execute()
79 | }
80 |
81 | func updateRecord() {
82 | update.execute()
83 | }
84 |
85 | func selectRecord() {
86 | select.execute()
87 | }
88 |
89 | func deleteRecord() {
90 | delete.execute()
91 | }
92 | }
93 | /*:
94 | ### Usage:
95 | */
96 | let database = Database()
97 | let insertCommand = InsertCommand(database: database)
98 | let updateCommand = UpdateCommand(database: database)
99 | let selectCommand = SelectCommand(database: database)
100 | let deleteCommand = DeleteCommand(database: database)
101 |
102 | let developer = Developer(insert: insertCommand, update: updateCommand, select: selectCommand, delete: deleteCommand)
103 | developer.insertRecord()
104 | developer.updateRecord()
105 | developer.selectRecord()
106 | developer.deleteRecord()
107 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Observer.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 👓 Observer
13 | -----------
14 |
15 | The observer pattern is used to allow an object to publish changes to its state.
16 | Other objects subscribe to be immediately notified of any changes.
17 |
18 | ### Example
19 | */
20 | protocol Observer {
21 | var name: String { get }
22 |
23 | func handleEvent(vacancies: [String])
24 | }
25 |
26 | protocol Observed {
27 | mutating func addObserver(observer: Observer)
28 | mutating func removeObserver(observer: Observer)
29 | func notifyObservers()
30 | }
31 |
32 | struct Subscriber: Observer {
33 | var name: String
34 |
35 | func handleEvent(vacancies: [String]) {
36 | print("Dear \(name). We have some changes in vacancies:\n\(vacancies)\n")
37 | }
38 | }
39 |
40 | struct HeadHunter: Observed {
41 | var vacancies = [String]()
42 | var subscribers = [Observer]()
43 |
44 | mutating func addVacancy(vacancy: String) {
45 | vacancies.append(vacancy)
46 | notifyObservers()
47 | }
48 |
49 | mutating func removeVacancy(vacancy: String) {
50 | if let index = vacancies.index(of: vacancy) {
51 | vacancies.remove(at: index)
52 | notifyObservers()
53 | }
54 | }
55 |
56 | mutating func addObserver(observer: Observer) {
57 | subscribers.append(observer)
58 | }
59 |
60 | mutating func removeObserver(observer: Observer) {
61 | for index in 1...subscribers.count - 1 {
62 | let subscriber = subscribers[index]
63 | if subscriber.name == observer.name {
64 | subscribers.remove(at: index)
65 | break
66 | }
67 | }
68 | }
69 |
70 | func notifyObservers() {
71 | for subscriber in subscribers {
72 | subscriber.handleEvent(vacancies: vacancies)
73 | }
74 | }
75 | }
76 | /*:
77 | ### Usage
78 | */
79 | var hh = HeadHunter()
80 | hh.addVacancy(vacancy: "Swift Developer")
81 | hh.addVacancy(vacancy: "ObjC Developer")
82 |
83 | let zsergey = Subscriber(name: "Sergey Zapuhlyak")
84 | let azimin = Subscriber(name: "Alex Zimin")
85 |
86 | hh.addObserver(observer: zsergey)
87 | hh.addObserver(observer: azimin)
88 |
89 | hh.addVacancy(vacancy: "C++ Developer")
90 |
91 | hh.removeObserver(observer: azimin)
92 | hh.removeVacancy(vacancy: "ObjC Developer")
93 | /*:
94 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer)
95 | */
96 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Visitor.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🏃 Visitor
13 | ----------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Developer {
20 | func create(project: ProjectClass)
21 | func create(project: Database)
22 | func create(project: Test)
23 | }
24 |
25 | protocol ProjectElement {
26 | func beWritten(developer: Developer)
27 | }
28 |
29 | struct ProjectClass: ProjectElement {
30 | func beWritten(developer: Developer) {
31 | developer.create(project: self)
32 | }
33 | }
34 |
35 | struct Database: ProjectElement {
36 | func beWritten(developer: Developer) {
37 | developer.create(project: self)
38 | }
39 | }
40 |
41 | struct Test: ProjectElement {
42 | func beWritten(developer: Developer) {
43 | developer.create(project: self)
44 | }
45 | }
46 |
47 | struct Project: ProjectElement {
48 | var projectElements: [ProjectElement] = [ProjectClass(), Database(), Test()]
49 |
50 | func beWritten(developer: Developer) {
51 | for projectElement in projectElements {
52 | projectElement.beWritten(developer: developer)
53 | }
54 | }
55 | }
56 |
57 | struct JuniorDeveloper: Developer {
58 | func create(project: ProjectClass) {
59 | print("Writing poor class...")
60 | }
61 |
62 | func create(project: Database) {
63 | print("Drop database...")
64 | }
65 |
66 | func create(project: Test) {
67 | print("Creating not reliable test...")
68 | }
69 | }
70 |
71 | struct SeniorDeveloper: Developer {
72 | func create(project: ProjectClass) {
73 | print("Rewriting class after junior...")
74 | }
75 |
76 | func create(project: Database) {
77 | print("Fixing database...")
78 | }
79 |
80 | func create(project: Test) {
81 | print("Creating reliable test...")
82 | }
83 | }
84 | /*:
85 | ### Usage
86 | */
87 | let project = Project()
88 | let junior = JuniorDeveloper()
89 | let senior = SeniorDeveloper()
90 |
91 | print("Junior in Action")
92 | project.beWritten(developer: junior)
93 |
94 | print("")
95 |
96 | print("Senior in Action")
97 | project.beWritten(developer: senior)
98 | /*:
99 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor)
100 | */
101 |
--------------------------------------------------------------------------------
/Behavioral.playground/Pages/Mediator.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 💐 Mediator
13 | -----------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Chat {
20 | func sendMessage(_ message: String, from user: User)
21 | }
22 |
23 | protocol User {
24 | var ID: Int { set get }
25 | var name: String { set get }
26 | var chat: Chat { set get }
27 | func sendMessage(_ message: String)
28 | func getMessage(_ message: String)
29 | }
30 |
31 | struct Admin: User {
32 | internal var ID: Int
33 | internal var name: String
34 | internal var chat: Chat
35 |
36 | func sendMessage(_ message: String) {
37 | chat.sendMessage(message, from: self)
38 | }
39 |
40 | func getMessage(_ message: String) {
41 | print("\(name) received message: \(message)")
42 | }
43 | }
44 |
45 | struct Client: User {
46 | internal var ID: Int
47 | internal var name: String
48 | internal var chat: Chat
49 |
50 | func sendMessage(_ message: String) {
51 | chat.sendMessage(message, from: self)
52 | }
53 |
54 | func getMessage(_ message: String) {
55 | print("\(name) received message: \(message)")
56 | }
57 | }
58 |
59 | class Telegram: Chat {
60 | var admin: Admin?
61 | var clients: [Client]?
62 |
63 | func addClient(client: Client) {
64 | if clients == nil {
65 | clients = [Client]()
66 | }
67 | clients?.append(client)
68 | }
69 |
70 | func sendMessage(_ message: String, from user: User) {
71 | if let clients = clients {
72 | for client in clients {
73 | if client.ID != user.ID {
74 | client.getMessage(message)
75 | }
76 | }
77 | }
78 |
79 | admin?.getMessage(message)
80 | }
81 | }
82 | /*:
83 | ### Usage
84 | */
85 | var telegram = Telegram()
86 | let admin = Admin(ID: 1, name: "Pavel Durov", chat: telegram)
87 | let zsergey = Client(ID: 2, name: "Sergey Zapuhlyak", chat: telegram)
88 | let azimin = Client(ID: 3, name: "Alex Zimin", chat: telegram)
89 | telegram.admin = admin
90 | telegram.addClient(client: zsergey)
91 | telegram.addClient(client: azimin)
92 |
93 | zsergey.sendMessage("Hello, I am Sergey Zapuhlyak")
94 | admin.sendMessage("I am Administrator!")
95 | /*:
96 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator)
97 | */
98 |
--------------------------------------------------------------------------------
/Creational.playground/Pages/Builder.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 👷 Builder
13 | ----------
14 |
15 | 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.
16 | An external class controls the construction algorithm.
17 |
18 | ### Example
19 | */
20 | enum Cms {
21 | case wordpress
22 | case alifresco
23 | }
24 |
25 | struct Website {
26 | var name: String?
27 | var cms: Cms?
28 | var price: Int?
29 |
30 | func printWebsite(){
31 | guard let name = name, let cms = cms, let price = price else {
32 | return
33 | }
34 | print("Name \(name), cms \(cms), price \(price)")
35 | }
36 | }
37 |
38 | protocol WebsiteBuilder {
39 | var website: Website? { set get }
40 | func createWebsite()
41 | func buildName()
42 | func buildCms()
43 | func buildPrice()
44 | }
45 |
46 | class VisitCardWebsiteBuilder: WebsiteBuilder {
47 | internal var website: Website?
48 |
49 | internal func createWebsite() {
50 | self.website = Website()
51 | }
52 |
53 | internal func buildName() {
54 | self.website?.name = "Visit Card"
55 | }
56 |
57 | internal func buildCms() {
58 | self.website?.cms = .wordpress
59 | }
60 |
61 | internal func buildPrice() {
62 | self.website?.price = 500
63 | }
64 | }
65 |
66 | class EnterpriseWebsiteBuilder: WebsiteBuilder {
67 | internal var website: Website?
68 |
69 | internal func createWebsite() {
70 | self.website = Website()
71 | }
72 |
73 | internal func buildName() {
74 | self.website?.name = "Enterprise website"
75 | }
76 |
77 | internal func buildCms() {
78 | self.website?.cms = .alifresco
79 | }
80 |
81 | internal func buildPrice() {
82 | self.website?.price = 10000
83 | }
84 | }
85 |
86 | struct Director {
87 | var builder: WebsiteBuilder
88 |
89 | func buildWebsite() -> Website {
90 | builder.createWebsite()
91 | builder.buildName()
92 | builder.buildCms()
93 | builder.buildPrice()
94 | return builder.website!
95 | }
96 | }
97 | /*:
98 | ### Usage
99 | */
100 | let director = Director(builder: EnterpriseWebsiteBuilder())
101 | let website = director.buildWebsite()
102 | website.printWebsite()
103 | /*:
104 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Builder)
105 | */
106 |
--------------------------------------------------------------------------------
/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 | protocol Developer {
11 | func writeCode()
12 | }
13 |
14 | protocol Tester {
15 | func testCode()
16 | }
17 |
18 | protocol ProjectManager {
19 | func manageProject()
20 | }
21 |
22 | protocol ProjectTeamFactory {
23 | var developer: Developer { get }
24 | var tester: Tester { get }
25 | var projectManager: ProjectManager { get }
26 | }
27 |
28 | // Team of Bank.
29 | struct SwiftDeveloper: Developer {
30 | func writeCode() {
31 | print("Swift developer writes Swift code...")
32 | }
33 | }
34 |
35 | struct QATester: Tester {
36 | func testCode() {
37 | print("QA tester tests banking code...")
38 | }
39 | }
40 |
41 | struct BankingPM: ProjectManager {
42 | func manageProject() {
43 | print("BankingPM manages banking project...")
44 | }
45 | }
46 |
47 | struct BankingTeamFactory: ProjectTeamFactory {
48 | var developer: Developer {
49 | return SwiftDeveloper()
50 | }
51 | var tester: Tester {
52 | return QATester()
53 | }
54 | var projectManager: ProjectManager {
55 | return BankingPM()
56 | }
57 | }
58 |
59 | // Team of Website.
60 | struct PhpDeveloper: Developer {
61 | func writeCode() {
62 | print("Php developer writes php code...")
63 | }
64 | }
65 |
66 | struct ManualTester: Tester {
67 | func testCode() {
68 | print("Manual tester tests Website...")
69 | }
70 | }
71 |
72 | struct WebsitePM: ProjectManager {
73 | func manageProject() {
74 | print("WebsitePM manages Website project...")
75 | }
76 | }
77 |
78 | struct WebsiteTeamFactory: ProjectTeamFactory {
79 | var developer: Developer {
80 | return PhpDeveloper()
81 | }
82 | var tester: Tester {
83 | return ManualTester()
84 | }
85 | var projectManager: ProjectManager {
86 | return WebsitePM()
87 | }
88 | }
89 |
90 | // Projects.
91 | enum Projects {
92 | case bankBusinessOnline
93 | case auctionSite
94 |
95 | var name: String {
96 | switch self {
97 | case .bankBusinessOnline:
98 | return "Bank business online"
99 | case .auctionSite:
100 | return "Auction site"
101 | }
102 | }
103 |
104 | var factory: ProjectTeamFactory {
105 | switch self {
106 | case .bankBusinessOnline:
107 | return BankingTeamFactory()
108 | case .auctionSite:
109 | return WebsiteTeamFactory()
110 | }
111 | }
112 |
113 | func createProject() {
114 | print("Создание проекта \(name)")
115 | let projectFactory = factory
116 | projectFactory.developer.writeCode()
117 | projectFactory.tester.testCode()
118 | projectFactory.projectManager.manageProject()
119 | }
120 | }
121 | /*:
122 | ### Usage
123 | */
124 | Projects.bankBusinessOnline.createProject()
125 | Projects.auctionSite.createProject()
126 |
--------------------------------------------------------------------------------
/Creational.playground/Pages/Abstract-Factory.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🌰 Abstract Factory
13 | -------------------
14 |
15 | The abstract factory pattern is used to provide a client with a set of related or dependant objects.
16 | The "family" of objects created by the factory are determined at run-time.
17 |
18 | ### Example
19 | */
20 | protocol Developer {
21 | func writeCode()
22 | }
23 |
24 | protocol Tester {
25 | func testCode()
26 | }
27 |
28 | protocol ProjectManager {
29 | func manageProject()
30 | }
31 |
32 | protocol ProjectTeamFactory {
33 | var developer: Developer { get }
34 | var tester: Tester { get }
35 | var projectManager: ProjectManager { get }
36 | }
37 |
38 | // Team of Bank.
39 | struct SwiftDeveloper: Developer {
40 | func writeCode() {
41 | print("Swift developer writes Swift code...")
42 | }
43 | }
44 |
45 | struct QATester: Tester {
46 | func testCode() {
47 | print("QA tester tests banking code...")
48 | }
49 | }
50 |
51 | struct BankingPM: ProjectManager {
52 | func manageProject() {
53 | print("BankingPM manages banking project...")
54 | }
55 | }
56 |
57 | struct BankingTeamFactory: ProjectTeamFactory {
58 | var developer: Developer {
59 | return SwiftDeveloper()
60 | }
61 | var tester: Tester {
62 | return QATester()
63 | }
64 | var projectManager: ProjectManager {
65 | return BankingPM()
66 | }
67 | }
68 |
69 | // Team of Website.
70 | struct PhpDeveloper: Developer {
71 | func writeCode() {
72 | print("Php developer writes php code...")
73 | }
74 | }
75 |
76 | struct ManualTester: Tester {
77 | func testCode() {
78 | print("Manual tester tests Website...")
79 | }
80 | }
81 |
82 | struct WebsitePM: ProjectManager {
83 | func manageProject() {
84 | print("WebsitePM manages Website project...")
85 | }
86 | }
87 |
88 | struct WebsiteTeamFactory: ProjectTeamFactory {
89 | var developer: Developer {
90 | return PhpDeveloper()
91 | }
92 | var tester: Tester {
93 | return ManualTester()
94 | }
95 | var projectManager: ProjectManager {
96 | return WebsitePM()
97 | }
98 | }
99 |
100 | // Projects.
101 | enum Projects {
102 | case bankBusinessOnline
103 | case auctionSite
104 |
105 | var name: String {
106 | switch self {
107 | case .bankBusinessOnline:
108 | return "Bank business online"
109 | case .auctionSite:
110 | return "Auction site"
111 | }
112 | }
113 |
114 | var factory: ProjectTeamFactory {
115 | switch self {
116 | case .bankBusinessOnline:
117 | return BankingTeamFactory()
118 | case .auctionSite:
119 | return WebsiteTeamFactory()
120 | }
121 | }
122 |
123 | func createProject() {
124 | print("Создание проекта \(name)")
125 | let projectFactory = factory
126 | projectFactory.developer.writeCode()
127 | projectFactory.tester.testCode()
128 | projectFactory.projectManager.manageProject()
129 | }
130 | }
131 | /*:
132 | ### Usage
133 | */
134 | Projects.bankBusinessOnline.createProject()
135 | Projects.auctionSite.createProject()
136 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🌰 Abstract Factory
13 | -------------------
14 |
15 | The abstract factory pattern is used to provide a client with a set of related or dependant objects.
16 | The "family" of objects created by the factory are determined at run-time.
17 |
18 | ### Example
19 | */
20 | protocol Developer {
21 | func writeCode()
22 | }
23 |
24 | protocol Tester {
25 | func testCode()
26 | }
27 |
28 | protocol ProjectManager {
29 | func manageProject()
30 | }
31 |
32 | protocol ProjectTeamFactory {
33 | var developer: Developer { get }
34 | var tester: Tester { get }
35 | var projectManager: ProjectManager { get }
36 | }
37 |
38 | // Team of Bank.
39 | struct SwiftDeveloper: Developer {
40 | func writeCode() {
41 | print("Swift developer writes Swift code...")
42 | }
43 | }
44 |
45 | struct QATester: Tester {
46 | func testCode() {
47 | print("QA tester tests banking code...")
48 | }
49 | }
50 |
51 | struct BankingPM: ProjectManager {
52 | func manageProject() {
53 | print("BankingPM manages banking project...")
54 | }
55 | }
56 |
57 | struct BankingTeamFactory: ProjectTeamFactory {
58 | var developer: Developer {
59 | return SwiftDeveloper()
60 | }
61 | var tester: Tester {
62 | return QATester()
63 | }
64 | var projectManager: ProjectManager {
65 | return BankingPM()
66 | }
67 | }
68 |
69 | // Team of Website.
70 | struct PhpDeveloper: Developer {
71 | func writeCode() {
72 | print("Php developer writes php code...")
73 | }
74 | }
75 |
76 | struct ManualTester: Tester {
77 | func testCode() {
78 | print("Manual tester tests Website...")
79 | }
80 | }
81 |
82 | struct WebsitePM: ProjectManager {
83 | func manageProject() {
84 | print("WebsitePM manages Website project...")
85 | }
86 | }
87 |
88 | struct WebsiteTeamFactory: ProjectTeamFactory {
89 | var developer: Developer {
90 | return PhpDeveloper()
91 | }
92 | var tester: Tester {
93 | return ManualTester()
94 | }
95 | var projectManager: ProjectManager {
96 | return WebsitePM()
97 | }
98 | }
99 |
100 | // Projects.
101 | enum Projects {
102 | case bankBusinessOnline
103 | case auctionSite
104 |
105 | var name: String {
106 | switch self {
107 | case .bankBusinessOnline:
108 | return "Bank business online"
109 | case .auctionSite:
110 | return "Auction site"
111 | }
112 | }
113 |
114 | var factory: ProjectTeamFactory {
115 | switch self {
116 | case .bankBusinessOnline:
117 | return BankingTeamFactory()
118 | case .auctionSite:
119 | return WebsiteTeamFactory()
120 | }
121 | }
122 |
123 | func createProject() {
124 | print("Создание проекта \(name)")
125 | let projectFactory = factory
126 | projectFactory.developer.writeCode()
127 | projectFactory.tester.testCode()
128 | projectFactory.projectManager.manageProject()
129 | }
130 | }
131 | /*:
132 | ### Usage
133 | */
134 | Projects.bankBusinessOnline.createProject()
135 | Projects.auctionSite.createProject()
136 | /*:
137 | 👷 Builder
138 | ----------
139 |
140 | 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.
141 | An external class controls the construction algorithm.
142 |
143 | ### Example
144 | */
145 | enum Cms {
146 | case wordpress
147 | case alifresco
148 | }
149 |
150 | struct Website {
151 | var name: String?
152 | var cms: Cms?
153 | var price: Int?
154 |
155 | func printWebsite(){
156 | guard let name = name, let cms = cms, let price = price else {
157 | return
158 | }
159 | print("Name \(name), cms \(cms), price \(price)")
160 | }
161 | }
162 |
163 | protocol WebsiteBuilder {
164 | var website: Website? { set get }
165 | func createWebsite()
166 | func buildName()
167 | func buildCms()
168 | func buildPrice()
169 | }
170 |
171 | class VisitCardWebsiteBuilder: WebsiteBuilder {
172 | internal var website: Website?
173 |
174 | internal func createWebsite() {
175 | self.website = Website()
176 | }
177 |
178 | internal func buildName() {
179 | self.website?.name = "Visit Card"
180 | }
181 |
182 | internal func buildCms() {
183 | self.website?.cms = .wordpress
184 | }
185 |
186 | internal func buildPrice() {
187 | self.website?.price = 500
188 | }
189 | }
190 |
191 | class EnterpriseWebsiteBuilder: WebsiteBuilder {
192 | internal var website: Website?
193 |
194 | internal func createWebsite() {
195 | self.website = Website()
196 | }
197 |
198 | internal func buildName() {
199 | self.website?.name = "Enterprise website"
200 | }
201 |
202 | internal func buildCms() {
203 | self.website?.cms = .alifresco
204 | }
205 |
206 | internal func buildPrice() {
207 | self.website?.price = 10000
208 | }
209 | }
210 |
211 | struct Director {
212 | var builder: WebsiteBuilder
213 |
214 | func buildWebsite() -> Website {
215 | builder.createWebsite()
216 | builder.buildName()
217 | builder.buildCms()
218 | builder.buildPrice()
219 | return builder.website!
220 | }
221 | }
222 | /*:
223 | ### Usage
224 | */
225 | let director = Director(builder: EnterpriseWebsiteBuilder())
226 | let website = director.buildWebsite()
227 | website.printWebsite()
228 | /*:
229 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Builder)
230 | */
231 | /*:
232 | 🏭 Factory Method
233 | -----------------
234 |
235 | 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.
236 |
237 | ### Example
238 | */
239 | protocol Developer {
240 | func writeCode()
241 | }
242 |
243 | struct ObjCDeveloper: Developer {
244 | func writeCode() {
245 | print("ObjC developer writes Objective C code...")
246 | }
247 | }
248 |
249 | struct SwiftDeveloper: Developer {
250 | func writeCode() {
251 | print("Swift developer writes Swift code...")
252 | }
253 | }
254 |
255 | protocol DeveloperFactory {
256 | func newDeveloper() -> Developer
257 | }
258 |
259 | struct ObjCDeveloperFactory: DeveloperFactory {
260 | func newDeveloper() -> Developer {
261 | return ObjCDeveloper()
262 | }
263 | }
264 |
265 | struct SwiftDeveloperFactory: DeveloperFactory {
266 | func newDeveloper() -> Developer {
267 | return SwiftDeveloper()
268 | }
269 | }
270 |
271 | enum Languages {
272 | case objC
273 | case swift
274 |
275 | var factory: DeveloperFactory {
276 | switch self {
277 | case .objC:
278 | return ObjCDeveloperFactory()
279 | case .swift:
280 | return SwiftDeveloperFactory()
281 | }
282 | }
283 | }
284 | /*:
285 | ### Usage
286 | */
287 | let developer = Languages.swift.factory.newDeveloper()
288 | developer.writeCode()
289 | /*:
290 | 🃏 Prototype
291 | ------------
292 |
293 | The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
294 | This practise is particularly useful when the construction of a new object is inefficient.
295 |
296 | ### Example
297 | */
298 | protocol Copyable {
299 | func copy() -> Any
300 | }
301 |
302 | struct Project: Copyable {
303 | var id: Int
304 | var name: String
305 | var source: String
306 |
307 | func copy() -> Any {
308 | let object = Project(id: id, name: name, source: source)
309 | return object
310 | }
311 | }
312 |
313 | struct ProjectFactory {
314 | var project: Project
315 | func cloneProject() -> Project {
316 | return project.copy() as! Project
317 | }
318 | }
319 | /*:
320 | ### Usage
321 | */
322 | let master = Project(id: 1, name: "Playground.swift", source: "let sourceCode = SourceCode()")
323 | let factory = ProjectFactory(project: master)
324 | let masterClone = factory.cloneProject()
325 | /*:
326 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Prototype)
327 | */
328 | /*:
329 | 💍 Singleton
330 | ------------
331 |
332 | The singleton pattern ensures that only one object of a particular class is ever created.
333 | All further references to objects of the singleton class refer to the same underlying instance.
334 | There are very few applications, do not overuse this pattern!
335 |
336 | ### Example:
337 | */
338 | struct Game {
339 | static let sharedGame = Game()
340 |
341 | private init() {
342 |
343 | }
344 | }
345 | /*:
346 | ### Usage:
347 | */
348 | let game = Game.sharedGame
349 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Structural.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🔌 Adapter
13 | ----------
14 |
15 | 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.
16 |
17 | ### Example
18 | */
19 | protocol Database {
20 | func insert()
21 | func update()
22 | func select()
23 | func remove()
24 | }
25 |
26 | class SwiftApp {
27 | func saveObject() {
28 | print("Saving Swift Object...")
29 | }
30 |
31 | func updateObject() {
32 | print("Updating Swift Object...")
33 | }
34 |
35 | func loadObject() {
36 | print("Loading Swift Object...")
37 | }
38 |
39 | func deleteObject() {
40 | print("Deleting Swift Object...")
41 | }
42 | }
43 |
44 | class AdapterSwiftAppToDatabase: SwiftApp, Database {
45 | func insert() {
46 | saveObject()
47 | }
48 |
49 | func update() {
50 | updateObject()
51 | }
52 |
53 | func select() {
54 | loadObject()
55 | }
56 |
57 | func remove() {
58 | deleteObject()
59 | }
60 | }
61 |
62 | struct DatabaseManager {
63 | var database: Database
64 | func run() {
65 | database.insert()
66 | database.update()
67 | database.select()
68 | database.remove()
69 | }
70 | }
71 | /*:
72 | ### Usage
73 | */
74 | let databaseManager = DatabaseManager(database: AdapterSwiftAppToDatabase())
75 | databaseManager.run()
76 | /*:
77 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Adapter)
78 | */
79 | /*:
80 | 🌉 Bridge
81 | ----------
82 |
83 | 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.
84 |
85 | ### Example
86 | */
87 | protocol Developer {
88 | func writeCode()
89 | }
90 |
91 | protocol Program {
92 | var developer: Developer { get set }
93 | func develop()
94 | }
95 |
96 | struct SwiftDeveloper: Developer {
97 | func writeCode() {
98 | print("Swift Developer writes Swift code...")
99 | }
100 | }
101 |
102 | struct ObjCDeveloper: Developer {
103 | func writeCode() {
104 | print("ObjC Developer writes Objective-C code...")
105 | }
106 | }
107 |
108 | struct BankSystem: Program {
109 | var developer: Developer
110 |
111 | func develop() {
112 | print("Bank System development in progress...")
113 | developer.writeCode()
114 | }
115 | }
116 |
117 | struct StockExchange: Program {
118 | var developer: Developer
119 |
120 | func develop() {
121 | print("Stock Exchange development in progress...")
122 | developer.writeCode()
123 | }
124 | }
125 | /*:
126 | ### Usage
127 | */
128 | let programs: [Program] = [BankSystem(developer: ObjCDeveloper()),
129 | StockExchange(developer: SwiftDeveloper())]
130 | for program in programs {
131 | program.develop()
132 | }
133 | /*:
134 | 🌿 Composite
135 | -------------
136 |
137 | 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.
138 |
139 | ### Example
140 | */
141 | protocol Developer {
142 | func writeCode()
143 | }
144 |
145 | protocol Team {
146 | var developers: [Developer] { set get }
147 | func addDeveloper(developer: Developer)
148 | func createProject()
149 | }
150 |
151 | struct SwiftDeveloper: Developer{
152 | func writeCode() {
153 | print("Swift Developer writes Swift code...")
154 | }
155 | }
156 |
157 | struct ObjCDeveloper: Developer{
158 | func writeCode() {
159 | print("ObjC Developer writes Objective-C code...")
160 | }
161 | }
162 |
163 | class BankTeam: Team {
164 | var developers = [Developer]()
165 |
166 | func addDeveloper(developer: Developer) {
167 | developers.append(developer)
168 | }
169 |
170 | func createProject() {
171 | for developer in developers {
172 | developer.writeCode()
173 | }
174 | }
175 | }
176 | /*:
177 | ### Usage:
178 | */
179 | let team = BankTeam()
180 | team.addDeveloper(developer: ObjCDeveloper())
181 | team.addDeveloper(developer: ObjCDeveloper())
182 | team.addDeveloper(developer: ObjCDeveloper())
183 | team.addDeveloper(developer: ObjCDeveloper())
184 | team.addDeveloper(developer: SwiftDeveloper())
185 | team.createProject()
186 | /*:
187 | 🍧 Decorator
188 | ------------
189 |
190 | 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.
191 | This provides a flexible alternative to using inheritance to modify behaviour.
192 |
193 | ### Example
194 | */
195 | protocol Developer {
196 | func makeJob() -> String
197 | }
198 |
199 | struct SwiftDeveloper: Developer {
200 | func makeJob() -> String {
201 | return "Write Swift code"
202 | }
203 | }
204 |
205 | class DeveloperDecorator: Developer {
206 | var developer: Developer
207 | func makeJob() -> String {
208 | return developer.makeJob()
209 | }
210 | init(developer: Developer) {
211 | self.developer = developer
212 | }
213 | }
214 |
215 | class SeniorSwiftDeveloper: DeveloperDecorator {
216 | let codeReview = "Make code review"
217 | override func makeJob() -> String {
218 | return super.makeJob() + " & " + codeReview
219 | }
220 | }
221 |
222 | class SwiftTeamLead: DeveloperDecorator {
223 | let sendWeekReport = "Send week report"
224 | override func makeJob() -> String {
225 | return super.makeJob() + " & " + sendWeekReport
226 | }
227 | }
228 | /*:
229 | ### Usage:
230 | */
231 | let developer = SwiftTeamLead(developer: SeniorSwiftDeveloper(developer: SwiftDeveloper()))
232 | print(developer.makeJob())
233 | /*:
234 | 🎁 Façade
235 | ---------
236 |
237 | The facade pattern is used to define a simplified interface to a more complex subsystem.
238 |
239 | ### Example
240 | */
241 | class Job {
242 | func doJob() {
243 | print("Job is progress...")
244 | }
245 | }
246 |
247 | class BugTracker {
248 | var isActiveSprint = false
249 |
250 | func startSprint() {
251 | print("Sprint is active")
252 | isActiveSprint = true
253 | }
254 |
255 | func stopSprint() {
256 | print("Sprint is not active")
257 | isActiveSprint = false
258 | }
259 | }
260 |
261 | class Developer {
262 | func doJobBeforeDeadline(bugTracker: BugTracker) {
263 | if bugTracker.isActiveSprint {
264 | print("Developer is solving problems...")
265 | } else {
266 | print("Developer is reading the news...")
267 | }
268 | }
269 | }
270 |
271 | class Workflow {
272 | let developer = Developer()
273 | let job = Job()
274 | let bugTracker = BugTracker()
275 | func solveProblems() {
276 | job.doJob()
277 | bugTracker.startSprint()
278 | developer.doJobBeforeDeadline(bugTracker: bugTracker)
279 | }
280 | }
281 | /*:
282 | ### Usage
283 | */
284 | let workflow = Workflow()
285 | workflow.solveProblems()
286 | /*:
287 | ## 🍃 Flyweight
288 | The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
289 | ### Example
290 | */
291 | protocol Developer {
292 | func writeCode()
293 | }
294 |
295 | struct SwiftDeveloper: Developer {
296 | func writeCode() {
297 | print("Swift Developer writes Swift code...")
298 | }
299 | }
300 |
301 | struct ObjCDeveloper: Developer {
302 | func writeCode() {
303 | print("ObjC Developer writes Objective-C code...")
304 | }
305 | }
306 |
307 | enum Languages: String {
308 | case Swift
309 | case ObjC
310 |
311 | var description: String {
312 | return self.rawValue
313 | }
314 | }
315 |
316 | struct DeveloperFactory {
317 | private var developers = [String: Developer]()
318 |
319 | mutating func developer(by language: Languages) -> Developer {
320 | if let value = developers[language.description] {
321 | return value
322 | } else {
323 | var value: Developer? = nil
324 | print("Hiring \(language.description) developer ")
325 | switch language {
326 | case .Swift:
327 | value = SwiftDeveloper()
328 | case .ObjC:
329 | value = ObjCDeveloper()
330 | }
331 | developers[language.description] = value
332 | return value!
333 | }
334 | }
335 | }
336 | /*:
337 | ### Usage
338 | */
339 | var developerFactory = DeveloperFactory()
340 | var developers = [Developer]()
341 | developers.append(developerFactory.developer(by: .Swift))
342 | developers.append(developerFactory.developer(by: .Swift))
343 | developers.append(developerFactory.developer(by: .Swift))
344 | developers.append(developerFactory.developer(by: .ObjC))
345 | developers.append(developerFactory.developer(by: .ObjC))
346 | developers.append(developerFactory.developer(by: .ObjC))
347 | for developer in developers {
348 | developer.writeCode()
349 | }
350 | /*:
351 | ☔ Proxy
352 | ------------------
353 |
354 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
355 |
356 | ### Example
357 | */
358 | protocol Project {
359 | func run()
360 | }
361 |
362 | struct RealProject: Project {
363 | var url: String
364 |
365 | func load() {
366 | print("Loading project from url \(url) ...")
367 | }
368 |
369 | init(url: String) {
370 | self.url = url
371 | load()
372 | }
373 |
374 | func run() {
375 | print("Running project \(url) ...")
376 | }
377 | }
378 |
379 | class ProxyProject: Project {
380 | var url: String
381 | var realProject: RealProject?
382 |
383 | func run() {
384 | if realProject == nil {
385 | realProject = RealProject(url: url)
386 | }
387 | realProject!.run()
388 | }
389 |
390 | init(url: String) {
391 | self.url = url
392 | }
393 | }
394 | /*:
395 | ### Usage
396 | */
397 | var project = ProxyProject(url: "https://github.com/zsergey/realProject")
398 | project.run()
399 |
--------------------------------------------------------------------------------
/Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift:
--------------------------------------------------------------------------------
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 | */
9 | import Swift
10 | import Foundation
11 | /*:
12 | 🐝 Chain Of Responsibility
13 | --------------------------
14 |
15 | The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
16 |
17 | ### Example:
18 | */
19 | protocol Notifier {
20 | var priority: Int { set get }
21 | var nextNotifier: Notifier? { set get }
22 | func write(_ message: String)
23 | }
24 |
25 | extension Notifier {
26 | func notifyManager(message: String, level: Int) {
27 | if level >= priority {
28 | write(message)
29 | }
30 | if let nextNotifie = self.nextNotifier {
31 | nextNotifie.notifyManager(message: message, level: level)
32 | }
33 | }
34 | }
35 |
36 | enum Priority {
37 | case routine
38 | case important
39 | case asSoonAsPossible
40 | }
41 |
42 | struct SimpleReportNotifier: Notifier {
43 | internal var nextNotifier: Notifier?
44 | internal var priority: Int
45 |
46 | func write(_ message: String) {
47 | print("Notifying using simple report: \(message)")
48 | }
49 | }
50 |
51 | struct EmailNotifier: Notifier {
52 | internal var nextNotifier: Notifier?
53 | internal var priority: Int
54 |
55 | func write(_ message: String) {
56 | print("Sending email: \(message)")
57 | }
58 | }
59 |
60 | struct SMSNotifier: Notifier {
61 | internal var nextNotifier: Notifier?
62 | internal var priority: Int
63 |
64 | func write(_ message: String) {
65 | print("Sending sms to manager: \(message)")
66 | }
67 | }
68 | /*:
69 | ### Usage
70 | */
71 | let smsNotifier = SMSNotifier(nextNotifier: nil, priority: Priority.asSoonAsPossible.hashValue)
72 | let emailNotifier = EmailNotifier(nextNotifier: smsNotifier, priority: Priority.important.hashValue)
73 | let reportNotifier = SimpleReportNotifier(nextNotifier: emailNotifier, priority: Priority.routine.hashValue)
74 |
75 | reportNotifier.notifyManager(message: "Everything is OK", level: Priority.routine.hashValue)
76 | reportNotifier.notifyManager(message: "Something went wrong", level: Priority.important.hashValue)
77 | reportNotifier.notifyManager(message: "Houston, we've had a problem here!", level: Priority.asSoonAsPossible.hashValue)
78 | /*:
79 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility)
80 | */
81 | /*:
82 | 👫 Command
83 | ----------
84 |
85 | 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.
86 |
87 | ### Example:
88 | */
89 | struct Database {
90 | func insert() {
91 | print("Inserting record...")
92 | }
93 |
94 | func update() {
95 | print("Updating record...")
96 | }
97 |
98 | func select() {
99 | print("Reading record...")
100 | }
101 |
102 | func delete() {
103 | print("Deleting record...")
104 | }
105 | }
106 |
107 | protocol Command {
108 | var database: Database { set get }
109 | func execute()
110 | }
111 |
112 | struct InsertCommand: Command {
113 | internal var database: Database
114 |
115 | func execute() {
116 | database.insert()
117 | }
118 | }
119 |
120 | struct UpdateCommand: Command {
121 | internal var database: Database
122 |
123 | func execute() {
124 | database.update()
125 | }
126 | }
127 |
128 | struct SelectCommand: Command {
129 | internal var database: Database
130 |
131 | func execute() {
132 | database.select()
133 | }
134 | }
135 |
136 | struct DeleteCommand: Command {
137 | internal var database: Database
138 |
139 | func execute() {
140 | database.delete()
141 | }
142 | }
143 |
144 | struct Developer {
145 | var insert, update, select, delete: Command
146 |
147 | func insertRecord() {
148 | insert.execute()
149 | }
150 |
151 | func updateRecord() {
152 | update.execute()
153 | }
154 |
155 | func selectRecord() {
156 | select.execute()
157 | }
158 |
159 | func deleteRecord() {
160 | delete.execute()
161 | }
162 | }
163 | /*:
164 | ### Usage:
165 | */
166 | let database = Database()
167 | let insertCommand = InsertCommand(database: database)
168 | let updateCommand = UpdateCommand(database: database)
169 | let selectCommand = SelectCommand(database: database)
170 | let deleteCommand = DeleteCommand(database: database)
171 |
172 | let developer = Developer(insert: insertCommand, update: updateCommand, select: selectCommand, delete: deleteCommand)
173 | developer.insertRecord()
174 | developer.updateRecord()
175 | developer.selectRecord()
176 | developer.deleteRecord()
177 | /*:
178 | 🎶 Interpreter
179 | --------------
180 |
181 | The interpreter pattern is used to evaluate sentences in a language.
182 |
183 | ### Example
184 | */
185 | protocol Expression {
186 | func interpret(_ context: String) -> Bool
187 | }
188 |
189 | struct AndExpression: Expression {
190 | var expression1: Expression
191 | var expression2: Expression
192 |
193 | func interpret(_ context: String) -> Bool {
194 | return expression1.interpret(context) && expression2.interpret(context)
195 | }
196 | }
197 |
198 | struct OrExpression: Expression {
199 | var expression1: Expression
200 | var expression2: Expression
201 |
202 | func interpret(_ context: String) -> Bool {
203 | return expression1.interpret(context) || expression2.interpret(context)
204 | }
205 | }
206 |
207 | struct TerminalExpression: Expression {
208 | var data: String
209 |
210 | func interpret(_ context: String) -> Bool {
211 | return context.contains(data)
212 | }
213 | }
214 | /*:
215 | ### Usage
216 | */
217 | struct Interpreter {
218 | static func getAppleExpression() -> Expression {
219 | let swift = TerminalExpression(data: "Swift")
220 | let objC = TerminalExpression(data: "Objective-C")
221 | return OrExpression(expression1: objC, expression2: swift)
222 | }
223 |
224 | static func getJavaEEExpression() -> Expression {
225 | let java = TerminalExpression(data: "Java")
226 | let spring = TerminalExpression(data: "Spring")
227 | return AndExpression(expression1: java, expression2: spring)
228 | }
229 | }
230 |
231 | let appleExpression = Interpreter.getAppleExpression()
232 | let javaExpression = Interpreter.getJavaEEExpression()
233 | print("Is Developer an Apple Developer \(appleExpression.interpret("Swift"))")
234 | print("Does developer knows Java EE \(javaExpression.interpret("Java Spring"))")
235 | /*:
236 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter)
237 | */
238 | /*:
239 | 🍫 Iterator
240 | -----------
241 |
242 | 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.
243 |
244 | ### Example:
245 | */
246 | protocol Iterator {
247 | func hasNext() -> Bool
248 | mutating func next() -> String
249 | }
250 |
251 | protocol Collection {
252 | func getIterator() -> Iterator
253 | }
254 |
255 | struct SwiftDeveloper: Collection {
256 | var name: String
257 | var skills: [String]
258 |
259 | private struct SkillIterator: Iterator {
260 | var index: Int
261 | var data: [String]
262 | func hasNext() -> Bool {
263 | return index < data.count
264 | }
265 | mutating func next() -> String {
266 | let result = data[index]
267 | index = index + 1
268 | return result
269 | }
270 | }
271 |
272 | func getIterator() -> Iterator {
273 | return SkillIterator(index: 0, data: skills)
274 | }
275 | }
276 | /*:
277 | ### Usage
278 | */
279 | let skills = ["Swift", "ObjC", "Sketch", "PM"]
280 | let swiftDeveloper = SwiftDeveloper(name: "Sergey Zapuhlyak", skills: skills)
281 | var iterator = swiftDeveloper.getIterator()
282 | print("Developer \(swiftDeveloper.name)")
283 | print("Skills")
284 | while iterator.hasNext() {
285 | print("\(iterator.next())")
286 | }
287 | /*:
288 | 💐 Mediator
289 | -----------
290 |
291 | 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.
292 |
293 | ### Example
294 | */
295 | protocol Chat {
296 | func sendMessage(_ message: String, from user: User)
297 | }
298 |
299 | protocol User {
300 | var ID: Int { set get }
301 | var name: String { set get }
302 | var chat: Chat { set get }
303 | func sendMessage(_ message: String)
304 | func getMessage(_ message: String)
305 | }
306 |
307 | struct Admin: User {
308 | internal var ID: Int
309 | internal var name: String
310 | internal var chat: Chat
311 |
312 | func sendMessage(_ message: String) {
313 | chat.sendMessage(message, from: self)
314 | }
315 |
316 | func getMessage(_ message: String) {
317 | print("\(name) received message: \(message)")
318 | }
319 | }
320 |
321 | struct Client: User {
322 | internal var ID: Int
323 | internal var name: String
324 | internal var chat: Chat
325 |
326 | func sendMessage(_ message: String) {
327 | chat.sendMessage(message, from: self)
328 | }
329 |
330 | func getMessage(_ message: String) {
331 | print("\(name) received message: \(message)")
332 | }
333 | }
334 |
335 | class Telegram: Chat {
336 | var admin: Admin?
337 | var clients: [Client]?
338 |
339 | func addClient(client: Client) {
340 | if clients == nil {
341 | clients = [Client]()
342 | }
343 | clients?.append(client)
344 | }
345 |
346 | func sendMessage(_ message: String, from user: User) {
347 | if let clients = clients {
348 | for client in clients {
349 | if client.ID != user.ID {
350 | client.getMessage(message)
351 | }
352 | }
353 | }
354 |
355 | admin?.getMessage(message)
356 | }
357 | }
358 | /*:
359 | ### Usage
360 | */
361 | var telegram = Telegram()
362 | let admin = Admin(ID: 1, name: "Pavel Durov", chat: telegram)
363 | let zsergey = Client(ID: 2, name: "Sergey Zapuhlyak", chat: telegram)
364 | let azimin = Client(ID: 3, name: "Alex Zimin", chat: telegram)
365 | telegram.admin = admin
366 | telegram.addClient(client: zsergey)
367 | telegram.addClient(client: azimin)
368 |
369 | zsergey.sendMessage("Hello, I am Sergey Zapuhlyak")
370 | admin.sendMessage("I am Administrator!")
371 | /*:
372 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator)
373 | */
374 | /*:
375 | 💾 Memento
376 | ----------
377 |
378 | 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.
379 |
380 | ### Example
381 | */
382 | struct Project {
383 | var version: String
384 | var code: String
385 |
386 | func save() -> Save {
387 | return Save(version: version, code: code)
388 | }
389 |
390 | mutating func load(save: Save) {
391 | version = save.version
392 | code = save.code
393 | }
394 |
395 | func description() -> String {
396 | return "Project version = \(version): \n'\(code)'\n"
397 | }
398 | }
399 |
400 | struct Save {
401 | var version: String
402 | var code: String
403 | }
404 |
405 | struct GithubRepo {
406 | var save: Save
407 | }
408 | /*:
409 | ### Usage
410 | */
411 | print("Creating new project. Version 1.0")
412 | var project = Project(version: "1.0", code: "let index = 0")
413 | print(project.description())
414 |
415 | print("Saving current version to github")
416 | let github = GithubRepo(save: project.save())
417 |
418 | print("Updating project to Version 1.1")
419 | print("Writing poor code...")
420 | print("Set version 1.1")
421 | project.version = "1.1"
422 | project.code = "let index = 0\nindex = 5"
423 | print(project.description())
424 |
425 | print("Something went wrong")
426 | print("Rolling back to Version 1.0")
427 |
428 | project.load(save: github.save)
429 | print("Project after rollback")
430 | print(project.description())
431 | /*:
432 | 👓 Observer
433 | -----------
434 |
435 | The observer pattern is used to allow an object to publish changes to its state.
436 | Other objects subscribe to be immediately notified of any changes.
437 |
438 | ### Example
439 | */
440 | protocol Observer {
441 | var name: String { get }
442 |
443 | func handleEvent(vacancies: [String])
444 | }
445 |
446 | protocol Observed {
447 | mutating func addObserver(observer: Observer)
448 | mutating func removeObserver(observer: Observer)
449 | func notifyObservers()
450 | }
451 |
452 | struct Subscriber: Observer {
453 | var name: String
454 |
455 | func handleEvent(vacancies: [String]) {
456 | print("Dear \(name). We have some changes in vacancies:\n\(vacancies)\n")
457 | }
458 | }
459 |
460 | struct HeadHunter: Observed {
461 | var vacancies = [String]()
462 | var subscribers = [Observer]()
463 |
464 | mutating func addVacancy(vacancy: String) {
465 | vacancies.append(vacancy)
466 | notifyObservers()
467 | }
468 |
469 | mutating func removeVacancy(vacancy: String) {
470 | if let index = vacancies.index(of: vacancy) {
471 | vacancies.remove(at: index)
472 | notifyObservers()
473 | }
474 | }
475 |
476 | mutating func addObserver(observer: Observer) {
477 | subscribers.append(observer)
478 | }
479 |
480 | mutating func removeObserver(observer: Observer) {
481 | for index in 1...subscribers.count - 1 {
482 | let subscriber = subscribers[index]
483 | if subscriber.name == observer.name {
484 | subscribers.remove(at: index)
485 | break
486 | }
487 | }
488 | }
489 |
490 | func notifyObservers() {
491 | for subscriber in subscribers {
492 | subscriber.handleEvent(vacancies: vacancies)
493 | }
494 | }
495 | }
496 | /*:
497 | ### Usage
498 | */
499 | var hh = HeadHunter()
500 | hh.addVacancy(vacancy: "Swift Developer")
501 | hh.addVacancy(vacancy: "ObjC Developer")
502 |
503 | let zsergey = Subscriber(name: "Sergey Zapuhlyak")
504 | let azimin = Subscriber(name: "Alex Zimin")
505 |
506 | hh.addObserver(observer: zsergey)
507 | hh.addObserver(observer: azimin)
508 |
509 | hh.addVacancy(vacancy: "C++ Developer")
510 |
511 | hh.removeObserver(observer: azimin)
512 | hh.removeVacancy(vacancy: "ObjC Developer")
513 | /*:
514 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer)
515 | */
516 | /*:
517 | 🐉 State
518 | ---------
519 |
520 | The state pattern is used to alter the behaviour of an object as its internal state changes.
521 | The pattern allows the class for an object to apparently change at run-time.
522 |
523 | ### Example
524 | */
525 | protocol Activity {
526 | func justDoIt()
527 | }
528 |
529 | struct Coding: Activity {
530 | func justDoIt() {
531 | print("Writing code...")
532 | }
533 | }
534 |
535 | struct Reading: Activity {
536 | func justDoIt() {
537 | print("Reading book...")
538 | }
539 | }
540 |
541 | struct Sleeping: Activity {
542 | func justDoIt() {
543 | print("Sleeping...")
544 | }
545 | }
546 |
547 | struct Training: Activity {
548 | func justDoIt() {
549 | print("Training...")
550 | }
551 | }
552 |
553 | struct Developer {
554 | var activity: Activity
555 |
556 | mutating func changeActivity() {
557 | if let _ = activity as? Sleeping {
558 | activity = Training()
559 | } else if let _ = activity as? Training {
560 | activity = Coding()
561 | } else if let _ = activity as? Coding {
562 | activity = Reading()
563 | } else if let _ = activity as? Reading {
564 | activity = Sleeping()
565 | }
566 | }
567 |
568 | func justDoIt() {
569 | activity.justDoIt()
570 | }
571 | }
572 | /*:
573 | ### Usage
574 | */
575 | let activity = Sleeping()
576 | var developer = Developer(activity: activity)
577 | for i in 0..<10 {
578 | developer.justDoIt()
579 | developer.changeActivity()
580 | }
581 | /*:
582 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State)
583 | */
584 | /*:
585 | 💡 Strategy
586 | -----------
587 |
588 | The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
589 |
590 | ### Example
591 | */
592 | protocol Activity {
593 | func justDoIt()
594 | }
595 |
596 | struct Coding: Activity {
597 | func justDoIt() {
598 | print("Writing code...")
599 | }
600 | }
601 |
602 | struct Reading: Activity {
603 | func justDoIt() {
604 | print("Reading book...")
605 | }
606 | }
607 |
608 | struct Sleeping: Activity {
609 | func justDoIt() {
610 | print("Sleeping...")
611 | }
612 | }
613 |
614 | struct Training: Activity {
615 | func justDoIt() {
616 | print("Training...")
617 | }
618 | }
619 |
620 | struct Developer {
621 | var activity: Activity
622 |
623 | func executeActivity() {
624 | activity.justDoIt()
625 | }
626 | }
627 | /*:
628 | ### Usage
629 | */
630 | var developer = Developer(activity: Sleeping())
631 | developer.executeActivity()
632 |
633 | developer.activity = Training()
634 | developer.executeActivity()
635 |
636 | developer.activity = Coding()
637 | developer.executeActivity()
638 |
639 | developer.activity = Reading()
640 | developer.executeActivity()
641 |
642 | developer.activity = Sleeping()
643 | developer.executeActivity()
644 | /*:
645 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy)
646 | */
647 | /*:
648 | 🐾 Template Method
649 | ----------
650 |
651 | The template method pattern is used to define the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.
652 |
653 | ### Example
654 | */
655 | protocol WebsiteTemplate {
656 | func showPageContent()
657 | }
658 |
659 | extension WebsiteTemplate {
660 | func showPage() {
661 | print("Header")
662 | showPageContent()
663 | print("Footer")
664 | }
665 | }
666 |
667 | struct WelcomePage: WebsiteTemplate {
668 | func showPageContent() {
669 | print("Welcome")
670 | }
671 | }
672 |
673 | struct NewsPage: WebsiteTemplate {
674 | func showPageContent() {
675 | print("News")
676 | }
677 | }
678 | /*:
679 | ### Usage
680 | */
681 | let welcomePage = WelcomePage()
682 | welcomePage.showPage()
683 | print("")
684 |
685 | let newsPage = NewsPage()
686 | newsPage.showPage()
687 | /*:
688 | 🏃 Visitor
689 | ----------
690 |
691 | 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.
692 |
693 | ### Example
694 | */
695 | protocol Developer {
696 | func create(project: ProjectClass)
697 | func create(project: Database)
698 | func create(project: Test)
699 | }
700 |
701 | protocol ProjectElement {
702 | func beWritten(developer: Developer)
703 | }
704 |
705 | struct ProjectClass: ProjectElement {
706 | func beWritten(developer: Developer) {
707 | developer.create(project: self)
708 | }
709 | }
710 |
711 | struct Database: ProjectElement {
712 | func beWritten(developer: Developer) {
713 | developer.create(project: self)
714 | }
715 | }
716 |
717 | struct Test: ProjectElement {
718 | func beWritten(developer: Developer) {
719 | developer.create(project: self)
720 | }
721 | }
722 |
723 | struct Project: ProjectElement {
724 | var projectElements: [ProjectElement] = [ProjectClass(), Database(), Test()]
725 |
726 | func beWritten(developer: Developer) {
727 | for projectElement in projectElements {
728 | projectElement.beWritten(developer: developer)
729 | }
730 | }
731 | }
732 |
733 | struct JuniorDeveloper: Developer {
734 | func create(project: ProjectClass) {
735 | print("Writing poor class...")
736 | }
737 |
738 | func create(project: Database) {
739 | print("Drop database...")
740 | }
741 |
742 | func create(project: Test) {
743 | print("Creating not reliable test...")
744 | }
745 | }
746 |
747 | struct SeniorDeveloper: Developer {
748 | func create(project: ProjectClass) {
749 | print("Rewriting class after junior...")
750 | }
751 |
752 | func create(project: Database) {
753 | print("Fixing database...")
754 | }
755 |
756 | func create(project: Test) {
757 | print("Creating reliable test...")
758 | }
759 | }
760 | /*:
761 | ### Usage
762 | */
763 | let project = Project()
764 | let junior = JuniorDeveloper()
765 | let senior = SeniorDeveloper()
766 |
767 | print("Junior in Action")
768 | project.beWritten(developer: junior)
769 |
770 | print("")
771 |
772 | print("Senior in Action")
773 | project.beWritten(developer: senior)
774 | /*:
775 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor)
776 | */
777 |
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Design Patterns implemented in Swift 3.1
3 | ========================================
4 | A short cheat-sheet with Xcode 8.3.2 Playground ([Design-Patterns.zip](https://raw.githubusercontent.com/zsergey/Design-Patterns-In-Swift/master/Design-Patterns.zip)).
5 |
6 | 👷 Project maintained by: [@zsergey](http://twitter.com/zsergey) (Sergey Zapuhlyak)
7 |
8 | 🚀 How to generate README, Playground and zip from source: [GENERATE.md](https://github.com/zsergey/Design-Patterns-In-Swift/blob/master/GENERATE.md)
9 |
10 | ## Table of Contents
11 |
12 | * [Behavioral](#behavioral)
13 | * [Creational](#creational)
14 | * [Structural](#structural)
15 |
16 |
17 | ```swift
18 |
19 | ```
20 |
21 | Behavioral
22 | ==========
23 |
24 | >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.
25 | >
26 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
27 |
28 | ```swift
29 |
30 | import Swift
31 | import Foundation
32 | ```
33 |
34 | 🐝 Chain Of Responsibility
35 | --------------------------
36 |
37 | The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
38 |
39 | ### Example:
40 |
41 | ```swift
42 |
43 | protocol Notifier {
44 | var priority: Int { set get }
45 | var nextNotifier: Notifier? { set get }
46 | func write(_ message: String)
47 | }
48 |
49 | extension Notifier {
50 | func notifyManager(message: String, level: Int) {
51 | if level >= priority {
52 | write(message)
53 | }
54 | if let nextNotifie = self.nextNotifier {
55 | nextNotifie.notifyManager(message: message, level: level)
56 | }
57 | }
58 | }
59 |
60 | enum Priority {
61 | case routine
62 | case important
63 | case asSoonAsPossible
64 | }
65 |
66 | struct SimpleReportNotifier: Notifier {
67 | internal var nextNotifier: Notifier?
68 | internal var priority: Int
69 |
70 | func write(_ message: String) {
71 | print("Notifying using simple report: \(message)")
72 | }
73 | }
74 |
75 | struct EmailNotifier: Notifier {
76 | internal var nextNotifier: Notifier?
77 | internal var priority: Int
78 |
79 | func write(_ message: String) {
80 | print("Sending email: \(message)")
81 | }
82 | }
83 |
84 | struct SMSNotifier: Notifier {
85 | internal var nextNotifier: Notifier?
86 | internal var priority: Int
87 |
88 | func write(_ message: String) {
89 | print("Sending sms to manager: \(message)")
90 | }
91 | }
92 | ```
93 |
94 | ### Usage
95 |
96 | ```swift
97 |
98 | let smsNotifier = SMSNotifier(nextNotifier: nil, priority: Priority.asSoonAsPossible.hashValue)
99 | let emailNotifier = EmailNotifier(nextNotifier: smsNotifier, priority: Priority.important.hashValue)
100 | let reportNotifier = SimpleReportNotifier(nextNotifier: emailNotifier, priority: Priority.routine.hashValue)
101 |
102 | reportNotifier.notifyManager(message: "Everything is OK", level: Priority.routine.hashValue)
103 | reportNotifier.notifyManager(message: "Something went wrong", level: Priority.important.hashValue)
104 | reportNotifier.notifyManager(message: "Houston, we've had a problem here!", level: Priority.asSoonAsPossible.hashValue)
105 | ```
106 |
107 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility)
108 |
109 | ```swift
110 |
111 | ```
112 |
113 | 👫 Command
114 | ----------
115 |
116 | 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.
117 |
118 | ### Example:
119 |
120 | ```swift
121 |
122 | struct Database {
123 | func insert() {
124 | print("Inserting record...")
125 | }
126 |
127 | func update() {
128 | print("Updating record...")
129 | }
130 |
131 | func select() {
132 | print("Reading record...")
133 | }
134 |
135 | func delete() {
136 | print("Deleting record...")
137 | }
138 | }
139 |
140 | protocol Command {
141 | var database: Database { set get }
142 | func execute()
143 | }
144 |
145 | struct InsertCommand: Command {
146 | internal var database: Database
147 |
148 | func execute() {
149 | database.insert()
150 | }
151 | }
152 |
153 | struct UpdateCommand: Command {
154 | internal var database: Database
155 |
156 | func execute() {
157 | database.update()
158 | }
159 | }
160 |
161 | struct SelectCommand: Command {
162 | internal var database: Database
163 |
164 | func execute() {
165 | database.select()
166 | }
167 | }
168 |
169 | struct DeleteCommand: Command {
170 | internal var database: Database
171 |
172 | func execute() {
173 | database.delete()
174 | }
175 | }
176 |
177 | struct Developer {
178 | var insert, update, select, delete: Command
179 |
180 | func insertRecord() {
181 | insert.execute()
182 | }
183 |
184 | func updateRecord() {
185 | update.execute()
186 | }
187 |
188 | func selectRecord() {
189 | select.execute()
190 | }
191 |
192 | func deleteRecord() {
193 | delete.execute()
194 | }
195 | }
196 | ```
197 |
198 | ### Usage:
199 |
200 | ```swift
201 |
202 | let database = Database()
203 | let insertCommand = InsertCommand(database: database)
204 | let updateCommand = UpdateCommand(database: database)
205 | let selectCommand = SelectCommand(database: database)
206 | let deleteCommand = DeleteCommand(database: database)
207 |
208 | let developer = Developer(insert: insertCommand, update: updateCommand, select: selectCommand, delete: deleteCommand)
209 | developer.insertRecord()
210 | developer.updateRecord()
211 | developer.selectRecord()
212 | developer.deleteRecord()
213 | ```
214 |
215 | 🎶 Interpreter
216 | --------------
217 |
218 | The interpreter pattern is used to evaluate sentences in a language.
219 |
220 | ### Example
221 |
222 | ```swift
223 |
224 | protocol Expression {
225 | func interpret(_ context: String) -> Bool
226 | }
227 |
228 | struct AndExpression: Expression {
229 | var expression1: Expression
230 | var expression2: Expression
231 |
232 | func interpret(_ context: String) -> Bool {
233 | return expression1.interpret(context) && expression2.interpret(context)
234 | }
235 | }
236 |
237 | struct OrExpression: Expression {
238 | var expression1: Expression
239 | var expression2: Expression
240 |
241 | func interpret(_ context: String) -> Bool {
242 | return expression1.interpret(context) || expression2.interpret(context)
243 | }
244 | }
245 |
246 | struct TerminalExpression: Expression {
247 | var data: String
248 |
249 | func interpret(_ context: String) -> Bool {
250 | return context.contains(data)
251 | }
252 | }
253 | ```
254 |
255 | ### Usage
256 |
257 | ```swift
258 |
259 | struct Interpreter {
260 | static func getAppleExpression() -> Expression {
261 | let swift = TerminalExpression(data: "Swift")
262 | let objC = TerminalExpression(data: "Objective-C")
263 | return OrExpression(expression1: objC, expression2: swift)
264 | }
265 |
266 | static func getJavaEEExpression() -> Expression {
267 | let java = TerminalExpression(data: "Java")
268 | let spring = TerminalExpression(data: "Spring")
269 | return AndExpression(expression1: java, expression2: spring)
270 | }
271 | }
272 |
273 | let appleExpression = Interpreter.getAppleExpression()
274 | let javaExpression = Interpreter.getJavaEEExpression()
275 | print("Is Developer an Apple Developer \(appleExpression.interpret("Swift"))")
276 | print("Does developer knows Java EE \(javaExpression.interpret("Java Spring"))")
277 | ```
278 |
279 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter)
280 |
281 | ```swift
282 |
283 | ```
284 |
285 | 🍫 Iterator
286 | -----------
287 |
288 | 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.
289 |
290 | ### Example:
291 |
292 | ```swift
293 |
294 | protocol Iterator {
295 | func hasNext() -> Bool
296 | mutating func next() -> String
297 | }
298 |
299 | protocol Collection {
300 | func getIterator() -> Iterator
301 | }
302 |
303 | struct SwiftDeveloper: Collection {
304 | var name: String
305 | var skills: [String]
306 |
307 | private struct SkillIterator: Iterator {
308 | var index: Int
309 | var data: [String]
310 | func hasNext() -> Bool {
311 | return index < data.count
312 | }
313 | mutating func next() -> String {
314 | let result = data[index]
315 | index = index + 1
316 | return result
317 | }
318 | }
319 |
320 | func getIterator() -> Iterator {
321 | return SkillIterator(index: 0, data: skills)
322 | }
323 | }
324 | ```
325 |
326 | ### Usage
327 |
328 | ```swift
329 |
330 | let skills = ["Swift", "ObjC", "Sketch", "PM"]
331 | let swiftDeveloper = SwiftDeveloper(name: "Sergey Zapuhlyak", skills: skills)
332 | var iterator = swiftDeveloper.getIterator()
333 | print("Developer \(swiftDeveloper.name)")
334 | print("Skills")
335 | while iterator.hasNext() {
336 | print("\(iterator.next())")
337 | }
338 | ```
339 |
340 | 💐 Mediator
341 | -----------
342 |
343 | 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.
344 |
345 | ### Example
346 |
347 | ```swift
348 |
349 | protocol Chat {
350 | func sendMessage(_ message: String, from user: User)
351 | }
352 |
353 | protocol User {
354 | var ID: Int { set get }
355 | var name: String { set get }
356 | var chat: Chat { set get }
357 | func sendMessage(_ message: String)
358 | func getMessage(_ message: String)
359 | }
360 |
361 | struct Admin: User {
362 | internal var ID: Int
363 | internal var name: String
364 | internal var chat: Chat
365 |
366 | func sendMessage(_ message: String) {
367 | chat.sendMessage(message, from: self)
368 | }
369 |
370 | func getMessage(_ message: String) {
371 | print("\(name) received message: \(message)")
372 | }
373 | }
374 |
375 | struct Client: User {
376 | internal var ID: Int
377 | internal var name: String
378 | internal var chat: Chat
379 |
380 | func sendMessage(_ message: String) {
381 | chat.sendMessage(message, from: self)
382 | }
383 |
384 | func getMessage(_ message: String) {
385 | print("\(name) received message: \(message)")
386 | }
387 | }
388 |
389 | class Telegram: Chat {
390 | var admin: Admin?
391 | var clients: [Client]?
392 |
393 | func addClient(client: Client) {
394 | if clients == nil {
395 | clients = [Client]()
396 | }
397 | clients?.append(client)
398 | }
399 |
400 | func sendMessage(_ message: String, from user: User) {
401 | if let clients = clients {
402 | for client in clients {
403 | if client.ID != user.ID {
404 | client.getMessage(message)
405 | }
406 | }
407 | }
408 |
409 | admin?.getMessage(message)
410 | }
411 | }
412 | ```
413 |
414 | ### Usage
415 |
416 | ```swift
417 |
418 | var telegram = Telegram()
419 | let admin = Admin(ID: 1, name: "Pavel Durov", chat: telegram)
420 | let zsergey = Client(ID: 2, name: "Sergey Zapuhlyak", chat: telegram)
421 | let azimin = Client(ID: 3, name: "Alex Zimin", chat: telegram)
422 | telegram.admin = admin
423 | telegram.addClient(client: zsergey)
424 | telegram.addClient(client: azimin)
425 |
426 | zsergey.sendMessage("Hello, I am Sergey Zapuhlyak")
427 | admin.sendMessage("I am Administrator!")
428 | ```
429 |
430 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator)
431 |
432 | ```swift
433 |
434 | ```
435 |
436 | 💾 Memento
437 | ----------
438 |
439 | 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.
440 |
441 | ### Example
442 |
443 | ```swift
444 |
445 | struct Project {
446 | var version: String
447 | var code: String
448 |
449 | func save() -> Save {
450 | return Save(version: version, code: code)
451 | }
452 |
453 | mutating func load(save: Save) {
454 | version = save.version
455 | code = save.code
456 | }
457 |
458 | func description() -> String {
459 | return "Project version = \(version): \n'\(code)'\n"
460 | }
461 | }
462 |
463 | struct Save {
464 | var version: String
465 | var code: String
466 | }
467 |
468 | struct GithubRepo {
469 | var save: Save
470 | }
471 | ```
472 |
473 | ### Usage
474 |
475 | ```swift
476 |
477 | print("Creating new project. Version 1.0")
478 | var project = Project(version: "1.0", code: "let index = 0")
479 | print(project.description())
480 |
481 | print("Saving current version to github")
482 | let github = GithubRepo(save: project.save())
483 |
484 | print("Updating project to Version 1.1")
485 | print("Writing poor code...")
486 | print("Set version 1.1")
487 | project.version = "1.1"
488 | project.code = "let index = 0\nindex = 5"
489 | print(project.description())
490 |
491 | print("Something went wrong")
492 | print("Rolling back to Version 1.0")
493 |
494 | project.load(save: github.save)
495 | print("Project after rollback")
496 | print(project.description())
497 | ```
498 |
499 | 👓 Observer
500 | -----------
501 |
502 | The observer pattern is used to allow an object to publish changes to its state.
503 | Other objects subscribe to be immediately notified of any changes.
504 |
505 | ### Example
506 |
507 | ```swift
508 |
509 | protocol Observer {
510 | var name: String { get }
511 |
512 | func handleEvent(vacancies: [String])
513 | }
514 |
515 | protocol Observed {
516 | mutating func addObserver(observer: Observer)
517 | mutating func removeObserver(observer: Observer)
518 | func notifyObservers()
519 | }
520 |
521 | struct Subscriber: Observer {
522 | var name: String
523 |
524 | func handleEvent(vacancies: [String]) {
525 | print("Dear \(name). We have some changes in vacancies:\n\(vacancies)\n")
526 | }
527 | }
528 |
529 | struct HeadHunter: Observed {
530 | var vacancies = [String]()
531 | var subscribers = [Observer]()
532 |
533 | mutating func addVacancy(vacancy: String) {
534 | vacancies.append(vacancy)
535 | notifyObservers()
536 | }
537 |
538 | mutating func removeVacancy(vacancy: String) {
539 | if let index = vacancies.index(of: vacancy) {
540 | vacancies.remove(at: index)
541 | notifyObservers()
542 | }
543 | }
544 |
545 | mutating func addObserver(observer: Observer) {
546 | subscribers.append(observer)
547 | }
548 |
549 | mutating func removeObserver(observer: Observer) {
550 | for index in 1...subscribers.count - 1 {
551 | let subscriber = subscribers[index]
552 | if subscriber.name == observer.name {
553 | subscribers.remove(at: index)
554 | break
555 | }
556 | }
557 | }
558 |
559 | func notifyObservers() {
560 | for subscriber in subscribers {
561 | subscriber.handleEvent(vacancies: vacancies)
562 | }
563 | }
564 | }
565 | ```
566 |
567 | ### Usage
568 |
569 | ```swift
570 |
571 | var hh = HeadHunter()
572 | hh.addVacancy(vacancy: "Swift Developer")
573 | hh.addVacancy(vacancy: "ObjC Developer")
574 |
575 | let zsergey = Subscriber(name: "Sergey Zapuhlyak")
576 | let azimin = Subscriber(name: "Alex Zimin")
577 |
578 | hh.addObserver(observer: zsergey)
579 | hh.addObserver(observer: azimin)
580 |
581 | hh.addVacancy(vacancy: "C++ Developer")
582 |
583 | hh.removeObserver(observer: azimin)
584 | hh.removeVacancy(vacancy: "ObjC Developer")
585 | ```
586 |
587 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer)
588 |
589 | ```swift
590 |
591 | ```
592 |
593 | 🐉 State
594 | ---------
595 |
596 | The state pattern is used to alter the behaviour of an object as its internal state changes.
597 | The pattern allows the class for an object to apparently change at run-time.
598 |
599 | ### Example
600 |
601 | ```swift
602 |
603 | protocol Activity {
604 | func justDoIt()
605 | }
606 |
607 | struct Coding: Activity {
608 | func justDoIt() {
609 | print("Writing code...")
610 | }
611 | }
612 |
613 | struct Reading: Activity {
614 | func justDoIt() {
615 | print("Reading book...")
616 | }
617 | }
618 |
619 | struct Sleeping: Activity {
620 | func justDoIt() {
621 | print("Sleeping...")
622 | }
623 | }
624 |
625 | struct Training: Activity {
626 | func justDoIt() {
627 | print("Training...")
628 | }
629 | }
630 |
631 | struct Developer {
632 | var activity: Activity
633 |
634 | mutating func changeActivity() {
635 | if let _ = activity as? Sleeping {
636 | activity = Training()
637 | } else if let _ = activity as? Training {
638 | activity = Coding()
639 | } else if let _ = activity as? Coding {
640 | activity = Reading()
641 | } else if let _ = activity as? Reading {
642 | activity = Sleeping()
643 | }
644 | }
645 |
646 | func justDoIt() {
647 | activity.justDoIt()
648 | }
649 | }
650 | ```
651 |
652 | ### Usage
653 |
654 | ```swift
655 |
656 | let activity = Sleeping()
657 | var developer = Developer(activity: activity)
658 | for i in 0..<10 {
659 | developer.justDoIt()
660 | developer.changeActivity()
661 | }
662 | ```
663 |
664 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State)
665 |
666 | ```swift
667 |
668 | ```
669 |
670 | 💡 Strategy
671 | -----------
672 |
673 | The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
674 |
675 | ### Example
676 |
677 | ```swift
678 |
679 | protocol Activity {
680 | func justDoIt()
681 | }
682 |
683 | struct Coding: Activity {
684 | func justDoIt() {
685 | print("Writing code...")
686 | }
687 | }
688 |
689 | struct Reading: Activity {
690 | func justDoIt() {
691 | print("Reading book...")
692 | }
693 | }
694 |
695 | struct Sleeping: Activity {
696 | func justDoIt() {
697 | print("Sleeping...")
698 | }
699 | }
700 |
701 | struct Training: Activity {
702 | func justDoIt() {
703 | print("Training...")
704 | }
705 | }
706 |
707 | struct Developer {
708 | var activity: Activity
709 |
710 | func executeActivity() {
711 | activity.justDoIt()
712 | }
713 | }
714 | ```
715 |
716 | ### Usage
717 |
718 | ```swift
719 |
720 | var developer = Developer(activity: Sleeping())
721 | developer.executeActivity()
722 |
723 | developer.activity = Training()
724 | developer.executeActivity()
725 |
726 | developer.activity = Coding()
727 | developer.executeActivity()
728 |
729 | developer.activity = Reading()
730 | developer.executeActivity()
731 |
732 | developer.activity = Sleeping()
733 | developer.executeActivity()
734 | ```
735 |
736 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy)
737 |
738 | ```swift
739 |
740 | ```
741 |
742 | 🐾 Template Method
743 | ----------
744 |
745 | The template method pattern is used to define the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.
746 |
747 | ### Example
748 |
749 | ```swift
750 |
751 | protocol WebsiteTemplate {
752 | func showPageContent()
753 | }
754 |
755 | extension WebsiteTemplate {
756 | func showPage() {
757 | print("Header")
758 | showPageContent()
759 | print("Footer")
760 | }
761 | }
762 |
763 | struct WelcomePage: WebsiteTemplate {
764 | func showPageContent() {
765 | print("Welcome")
766 | }
767 | }
768 |
769 | struct NewsPage: WebsiteTemplate {
770 | func showPageContent() {
771 | print("News")
772 | }
773 | }
774 | ```
775 |
776 | ### Usage
777 |
778 | ```swift
779 |
780 | let welcomePage = WelcomePage()
781 | welcomePage.showPage()
782 | print("")
783 |
784 | let newsPage = NewsPage()
785 | newsPage.showPage()
786 | ```
787 |
788 | 🏃 Visitor
789 | ----------
790 |
791 | 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.
792 |
793 | ### Example
794 |
795 | ```swift
796 |
797 | protocol Developer {
798 | func create(project: ProjectClass)
799 | func create(project: Database)
800 | func create(project: Test)
801 | }
802 |
803 | protocol ProjectElement {
804 | func beWritten(developer: Developer)
805 | }
806 |
807 | struct ProjectClass: ProjectElement {
808 | func beWritten(developer: Developer) {
809 | developer.create(project: self)
810 | }
811 | }
812 |
813 | struct Database: ProjectElement {
814 | func beWritten(developer: Developer) {
815 | developer.create(project: self)
816 | }
817 | }
818 |
819 | struct Test: ProjectElement {
820 | func beWritten(developer: Developer) {
821 | developer.create(project: self)
822 | }
823 | }
824 |
825 | struct Project: ProjectElement {
826 | var projectElements: [ProjectElement] = [ProjectClass(), Database(), Test()]
827 |
828 | func beWritten(developer: Developer) {
829 | for projectElement in projectElements {
830 | projectElement.beWritten(developer: developer)
831 | }
832 | }
833 | }
834 |
835 | struct JuniorDeveloper: Developer {
836 | func create(project: ProjectClass) {
837 | print("Writing poor class...")
838 | }
839 |
840 | func create(project: Database) {
841 | print("Drop database...")
842 | }
843 |
844 | func create(project: Test) {
845 | print("Creating not reliable test...")
846 | }
847 | }
848 |
849 | struct SeniorDeveloper: Developer {
850 | func create(project: ProjectClass) {
851 | print("Rewriting class after junior...")
852 | }
853 |
854 | func create(project: Database) {
855 | print("Fixing database...")
856 | }
857 |
858 | func create(project: Test) {
859 | print("Creating reliable test...")
860 | }
861 | }
862 | ```
863 |
864 | ### Usage
865 |
866 | ```swift
867 |
868 | let project = Project()
869 | let junior = JuniorDeveloper()
870 | let senior = SeniorDeveloper()
871 |
872 | print("Junior in Action")
873 | project.beWritten(developer: junior)
874 |
875 | print("")
876 |
877 | print("Senior in Action")
878 | project.beWritten(developer: senior)
879 | ```
880 |
881 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor)
882 |
883 | ```swift
884 |
885 | ```
886 |
887 | Creational
888 | ==========
889 |
890 | > 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.
891 | >
892 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)
893 |
894 | ```swift
895 |
896 | import Swift
897 | import Foundation
898 | ```
899 |
900 | 🌰 Abstract Factory
901 | -------------------
902 |
903 | The abstract factory pattern is used to provide a client with a set of related or dependant objects.
904 | The "family" of objects created by the factory are determined at run-time.
905 |
906 | ### Example
907 |
908 | ```swift
909 |
910 | protocol Developer {
911 | func writeCode()
912 | }
913 |
914 | protocol Tester {
915 | func testCode()
916 | }
917 |
918 | protocol ProjectManager {
919 | func manageProject()
920 | }
921 |
922 | protocol ProjectTeamFactory {
923 | var developer: Developer { get }
924 | var tester: Tester { get }
925 | var projectManager: ProjectManager { get }
926 | }
927 |
928 | // Team of Bank.
929 | struct SwiftDeveloper: Developer {
930 | func writeCode() {
931 | print("Swift developer writes Swift code...")
932 | }
933 | }
934 |
935 | struct QATester: Tester {
936 | func testCode() {
937 | print("QA tester tests banking code...")
938 | }
939 | }
940 |
941 | struct BankingPM: ProjectManager {
942 | func manageProject() {
943 | print("BankingPM manages banking project...")
944 | }
945 | }
946 |
947 | struct BankingTeamFactory: ProjectTeamFactory {
948 | var developer: Developer {
949 | return SwiftDeveloper()
950 | }
951 | var tester: Tester {
952 | return QATester()
953 | }
954 | var projectManager: ProjectManager {
955 | return BankingPM()
956 | }
957 | }
958 |
959 | // Team of Website.
960 | struct PhpDeveloper: Developer {
961 | func writeCode() {
962 | print("Php developer writes php code...")
963 | }
964 | }
965 |
966 | struct ManualTester: Tester {
967 | func testCode() {
968 | print("Manual tester tests Website...")
969 | }
970 | }
971 |
972 | struct WebsitePM: ProjectManager {
973 | func manageProject() {
974 | print("WebsitePM manages Website project...")
975 | }
976 | }
977 |
978 | struct WebsiteTeamFactory: ProjectTeamFactory {
979 | var developer: Developer {
980 | return PhpDeveloper()
981 | }
982 | var tester: Tester {
983 | return ManualTester()
984 | }
985 | var projectManager: ProjectManager {
986 | return WebsitePM()
987 | }
988 | }
989 |
990 | // Projects.
991 | enum Projects {
992 | case bankBusinessOnline
993 | case auctionSite
994 |
995 | var name: String {
996 | switch self {
997 | case .bankBusinessOnline:
998 | return "Bank business online"
999 | case .auctionSite:
1000 | return "Auction site"
1001 | }
1002 | }
1003 |
1004 | var factory: ProjectTeamFactory {
1005 | switch self {
1006 | case .bankBusinessOnline:
1007 | return BankingTeamFactory()
1008 | case .auctionSite:
1009 | return WebsiteTeamFactory()
1010 | }
1011 | }
1012 |
1013 | func createProject() {
1014 | print("Создание проекта \(name)")
1015 | let projectFactory = factory
1016 | projectFactory.developer.writeCode()
1017 | projectFactory.tester.testCode()
1018 | projectFactory.projectManager.manageProject()
1019 | }
1020 | }
1021 | ```
1022 |
1023 | ### Usage
1024 |
1025 | ```swift
1026 |
1027 | Projects.bankBusinessOnline.createProject()
1028 | Projects.auctionSite.createProject()
1029 | ```
1030 |
1031 | 👷 Builder
1032 | ----------
1033 |
1034 | 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.
1035 | An external class controls the construction algorithm.
1036 |
1037 | ### Example
1038 |
1039 | ```swift
1040 |
1041 | enum Cms {
1042 | case wordpress
1043 | case alifresco
1044 | }
1045 |
1046 | struct Website {
1047 | var name: String?
1048 | var cms: Cms?
1049 | var price: Int?
1050 |
1051 | func printWebsite(){
1052 | guard let name = name, let cms = cms, let price = price else {
1053 | return
1054 | }
1055 | print("Name \(name), cms \(cms), price \(price)")
1056 | }
1057 | }
1058 |
1059 | protocol WebsiteBuilder {
1060 | var website: Website? { set get }
1061 | func createWebsite()
1062 | func buildName()
1063 | func buildCms()
1064 | func buildPrice()
1065 | }
1066 |
1067 | class VisitCardWebsiteBuilder: WebsiteBuilder {
1068 | internal var website: Website?
1069 |
1070 | internal func createWebsite() {
1071 | self.website = Website()
1072 | }
1073 |
1074 | internal func buildName() {
1075 | self.website?.name = "Visit Card"
1076 | }
1077 |
1078 | internal func buildCms() {
1079 | self.website?.cms = .wordpress
1080 | }
1081 |
1082 | internal func buildPrice() {
1083 | self.website?.price = 500
1084 | }
1085 | }
1086 |
1087 | class EnterpriseWebsiteBuilder: WebsiteBuilder {
1088 | internal var website: Website?
1089 |
1090 | internal func createWebsite() {
1091 | self.website = Website()
1092 | }
1093 |
1094 | internal func buildName() {
1095 | self.website?.name = "Enterprise website"
1096 | }
1097 |
1098 | internal func buildCms() {
1099 | self.website?.cms = .alifresco
1100 | }
1101 |
1102 | internal func buildPrice() {
1103 | self.website?.price = 10000
1104 | }
1105 | }
1106 |
1107 | struct Director {
1108 | var builder: WebsiteBuilder
1109 |
1110 | func buildWebsite() -> Website {
1111 | builder.createWebsite()
1112 | builder.buildName()
1113 | builder.buildCms()
1114 | builder.buildPrice()
1115 | return builder.website!
1116 | }
1117 | }
1118 | ```
1119 |
1120 | ### Usage
1121 |
1122 | ```swift
1123 |
1124 | let director = Director(builder: EnterpriseWebsiteBuilder())
1125 | let website = director.buildWebsite()
1126 | website.printWebsite()
1127 | ```
1128 |
1129 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Builder)
1130 |
1131 | ```swift
1132 |
1133 | ```
1134 |
1135 | 🏭 Factory Method
1136 | -----------------
1137 |
1138 | 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.
1139 |
1140 | ### Example
1141 |
1142 | ```swift
1143 |
1144 | protocol Developer {
1145 | func writeCode()
1146 | }
1147 |
1148 | struct ObjCDeveloper: Developer {
1149 | func writeCode() {
1150 | print("ObjC developer writes Objective C code...")
1151 | }
1152 | }
1153 |
1154 | struct SwiftDeveloper: Developer {
1155 | func writeCode() {
1156 | print("Swift developer writes Swift code...")
1157 | }
1158 | }
1159 |
1160 | protocol DeveloperFactory {
1161 | func newDeveloper() -> Developer
1162 | }
1163 |
1164 | struct ObjCDeveloperFactory: DeveloperFactory {
1165 | func newDeveloper() -> Developer {
1166 | return ObjCDeveloper()
1167 | }
1168 | }
1169 |
1170 | struct SwiftDeveloperFactory: DeveloperFactory {
1171 | func newDeveloper() -> Developer {
1172 | return SwiftDeveloper()
1173 | }
1174 | }
1175 |
1176 | enum Languages {
1177 | case objC
1178 | case swift
1179 |
1180 | var factory: DeveloperFactory {
1181 | switch self {
1182 | case .objC:
1183 | return ObjCDeveloperFactory()
1184 | case .swift:
1185 | return SwiftDeveloperFactory()
1186 | }
1187 | }
1188 | }
1189 | ```
1190 |
1191 | ### Usage
1192 |
1193 | ```swift
1194 |
1195 | let developer = Languages.swift.factory.newDeveloper()
1196 | developer.writeCode()
1197 | ```
1198 |
1199 | 🃏 Prototype
1200 | ------------
1201 |
1202 | The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
1203 | This practise is particularly useful when the construction of a new object is inefficient.
1204 |
1205 | ### Example
1206 |
1207 | ```swift
1208 |
1209 | protocol Copyable {
1210 | func copy() -> Any
1211 | }
1212 |
1213 | struct Project: Copyable {
1214 | var id: Int
1215 | var name: String
1216 | var source: String
1217 |
1218 | func copy() -> Any {
1219 | let object = Project(id: id, name: name, source: source)
1220 | return object
1221 | }
1222 | }
1223 |
1224 | struct ProjectFactory {
1225 | var project: Project
1226 | func cloneProject() -> Project {
1227 | return project.copy() as! Project
1228 | }
1229 | }
1230 | ```
1231 |
1232 | ### Usage
1233 |
1234 | ```swift
1235 |
1236 | let master = Project(id: 1, name: "Playground.swift", source: "let sourceCode = SourceCode()")
1237 | let factory = ProjectFactory(project: master)
1238 | let masterClone = factory.cloneProject()
1239 | ```
1240 |
1241 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Prototype)
1242 |
1243 | ```swift
1244 |
1245 | ```
1246 |
1247 | 💍 Singleton
1248 | ------------
1249 |
1250 | The singleton pattern ensures that only one object of a particular class is ever created.
1251 | All further references to objects of the singleton class refer to the same underlying instance.
1252 | There are very few applications, do not overuse this pattern!
1253 |
1254 | ### Example:
1255 |
1256 | ```swift
1257 |
1258 | struct Game {
1259 | static let sharedGame = Game()
1260 |
1261 | private init() {
1262 |
1263 | }
1264 | }
1265 | ```
1266 |
1267 | ### Usage:
1268 |
1269 | ```swift
1270 |
1271 | let game = Game.sharedGame
1272 | ```
1273 |
1274 | Structural
1275 | ==========
1276 |
1277 | >In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
1278 | >
1279 | >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)
1280 |
1281 | ```swift
1282 |
1283 | import Swift
1284 | import Foundation
1285 | ```
1286 |
1287 | 🔌 Adapter
1288 | ----------
1289 |
1290 | 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.
1291 |
1292 | ### Example
1293 |
1294 | ```swift
1295 |
1296 | protocol Database {
1297 | func insert()
1298 | func update()
1299 | func select()
1300 | func remove()
1301 | }
1302 |
1303 | class SwiftApp {
1304 | func saveObject() {
1305 | print("Saving Swift Object...")
1306 | }
1307 |
1308 | func updateObject() {
1309 | print("Updating Swift Object...")
1310 | }
1311 |
1312 | func loadObject() {
1313 | print("Loading Swift Object...")
1314 | }
1315 |
1316 | func deleteObject() {
1317 | print("Deleting Swift Object...")
1318 | }
1319 | }
1320 |
1321 | class AdapterSwiftAppToDatabase: SwiftApp, Database {
1322 | func insert() {
1323 | saveObject()
1324 | }
1325 |
1326 | func update() {
1327 | updateObject()
1328 | }
1329 |
1330 | func select() {
1331 | loadObject()
1332 | }
1333 |
1334 | func remove() {
1335 | deleteObject()
1336 | }
1337 | }
1338 |
1339 | struct DatabaseManager {
1340 | var database: Database
1341 | func run() {
1342 | database.insert()
1343 | database.update()
1344 | database.select()
1345 | database.remove()
1346 | }
1347 | }
1348 | ```
1349 |
1350 | ### Usage
1351 |
1352 | ```swift
1353 |
1354 | let databaseManager = DatabaseManager(database: AdapterSwiftAppToDatabase())
1355 | databaseManager.run()
1356 | ```
1357 |
1358 | >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Adapter)
1359 |
1360 | ```swift
1361 |
1362 | ```
1363 |
1364 | 🌉 Bridge
1365 | ----------
1366 |
1367 | 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.
1368 |
1369 | ### Example
1370 |
1371 | ```swift
1372 |
1373 | protocol Developer {
1374 | func writeCode()
1375 | }
1376 |
1377 | protocol Program {
1378 | var developer: Developer { get set }
1379 | func develop()
1380 | }
1381 |
1382 | struct SwiftDeveloper: Developer {
1383 | func writeCode() {
1384 | print("Swift Developer writes Swift code...")
1385 | }
1386 | }
1387 |
1388 | struct ObjCDeveloper: Developer {
1389 | func writeCode() {
1390 | print("ObjC Developer writes Objective-C code...")
1391 | }
1392 | }
1393 |
1394 | struct BankSystem: Program {
1395 | var developer: Developer
1396 |
1397 | func develop() {
1398 | print("Bank System development in progress...")
1399 | developer.writeCode()
1400 | }
1401 | }
1402 |
1403 | struct StockExchange: Program {
1404 | var developer: Developer
1405 |
1406 | func develop() {
1407 | print("Stock Exchange development in progress...")
1408 | developer.writeCode()
1409 | }
1410 | }
1411 | ```
1412 |
1413 | ### Usage
1414 |
1415 | ```swift
1416 |
1417 | let programs: [Program] = [BankSystem(developer: ObjCDeveloper()),
1418 | StockExchange(developer: SwiftDeveloper())]
1419 | for program in programs {
1420 | program.develop()
1421 | }
1422 | ```
1423 |
1424 | 🌿 Composite
1425 | -------------
1426 |
1427 | 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.
1428 |
1429 | ### Example
1430 |
1431 | ```swift
1432 |
1433 | protocol Developer {
1434 | func writeCode()
1435 | }
1436 |
1437 | protocol Team {
1438 | var developers: [Developer] { set get }
1439 | func addDeveloper(developer: Developer)
1440 | func createProject()
1441 | }
1442 |
1443 | struct SwiftDeveloper: Developer{
1444 | func writeCode() {
1445 | print("Swift Developer writes Swift code...")
1446 | }
1447 | }
1448 |
1449 | struct ObjCDeveloper: Developer{
1450 | func writeCode() {
1451 | print("ObjC Developer writes Objective-C code...")
1452 | }
1453 | }
1454 |
1455 | class BankTeam: Team {
1456 | var developers = [Developer]()
1457 |
1458 | func addDeveloper(developer: Developer) {
1459 | developers.append(developer)
1460 | }
1461 |
1462 | func createProject() {
1463 | for developer in developers {
1464 | developer.writeCode()
1465 | }
1466 | }
1467 | }
1468 | ```
1469 |
1470 | ### Usage:
1471 |
1472 | ```swift
1473 |
1474 | let team = BankTeam()
1475 | team.addDeveloper(developer: ObjCDeveloper())
1476 | team.addDeveloper(developer: ObjCDeveloper())
1477 | team.addDeveloper(developer: ObjCDeveloper())
1478 | team.addDeveloper(developer: ObjCDeveloper())
1479 | team.addDeveloper(developer: SwiftDeveloper())
1480 | team.createProject()
1481 | ```
1482 |
1483 | 🍧 Decorator
1484 | ------------
1485 |
1486 | 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.
1487 | This provides a flexible alternative to using inheritance to modify behaviour.
1488 |
1489 | ### Example
1490 |
1491 | ```swift
1492 |
1493 | protocol Developer {
1494 | func makeJob() -> String
1495 | }
1496 |
1497 | struct SwiftDeveloper: Developer {
1498 | func makeJob() -> String {
1499 | return "Write Swift code"
1500 | }
1501 | }
1502 |
1503 | class DeveloperDecorator: Developer {
1504 | var developer: Developer
1505 | func makeJob() -> String {
1506 | return developer.makeJob()
1507 | }
1508 | init(developer: Developer) {
1509 | self.developer = developer
1510 | }
1511 | }
1512 |
1513 | class SeniorSwiftDeveloper: DeveloperDecorator {
1514 | let codeReview = "Make code review"
1515 | override func makeJob() -> String {
1516 | return super.makeJob() + " & " + codeReview
1517 | }
1518 | }
1519 |
1520 | class SwiftTeamLead: DeveloperDecorator {
1521 | let sendWeekReport = "Send week report"
1522 | override func makeJob() -> String {
1523 | return super.makeJob() + " & " + sendWeekReport
1524 | }
1525 | }
1526 | ```
1527 |
1528 | ### Usage:
1529 |
1530 | ```swift
1531 |
1532 | let developer = SwiftTeamLead(developer: SeniorSwiftDeveloper(developer: SwiftDeveloper()))
1533 | print(developer.makeJob())
1534 | ```
1535 |
1536 | 🎁 Façade
1537 | ---------
1538 |
1539 | The facade pattern is used to define a simplified interface to a more complex subsystem.
1540 |
1541 | ### Example
1542 |
1543 | ```swift
1544 |
1545 | class Job {
1546 | func doJob() {
1547 | print("Job is progress...")
1548 | }
1549 | }
1550 |
1551 | class BugTracker {
1552 | var isActiveSprint = false
1553 |
1554 | func startSprint() {
1555 | print("Sprint is active")
1556 | isActiveSprint = true
1557 | }
1558 |
1559 | func stopSprint() {
1560 | print("Sprint is not active")
1561 | isActiveSprint = false
1562 | }
1563 | }
1564 |
1565 | class Developer {
1566 | func doJobBeforeDeadline(bugTracker: BugTracker) {
1567 | if bugTracker.isActiveSprint {
1568 | print("Developer is solving problems...")
1569 | } else {
1570 | print("Developer is reading the news...")
1571 | }
1572 | }
1573 | }
1574 |
1575 | class Workflow {
1576 | let developer = Developer()
1577 | let job = Job()
1578 | let bugTracker = BugTracker()
1579 | func solveProblems() {
1580 | job.doJob()
1581 | bugTracker.startSprint()
1582 | developer.doJobBeforeDeadline(bugTracker: bugTracker)
1583 | }
1584 | }
1585 | ```
1586 |
1587 | ### Usage
1588 |
1589 | ```swift
1590 |
1591 | let workflow = Workflow()
1592 | workflow.solveProblems()
1593 | ```
1594 |
1595 | ## 🍃 Flyweight
1596 | The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
1597 | ### Example
1598 |
1599 | ```swift
1600 |
1601 | protocol Developer {
1602 | func writeCode()
1603 | }
1604 |
1605 | struct SwiftDeveloper: Developer {
1606 | func writeCode() {
1607 | print("Swift Developer writes Swift code...")
1608 | }
1609 | }
1610 |
1611 | struct ObjCDeveloper: Developer {
1612 | func writeCode() {
1613 | print("ObjC Developer writes Objective-C code...")
1614 | }
1615 | }
1616 |
1617 | enum Languages: String {
1618 | case Swift
1619 | case ObjC
1620 |
1621 | var description: String {
1622 | return self.rawValue
1623 | }
1624 | }
1625 |
1626 | struct DeveloperFactory {
1627 | private var developers = [String: Developer]()
1628 |
1629 | mutating func developer(by language: Languages) -> Developer {
1630 | if let value = developers[language.description] {
1631 | return value
1632 | } else {
1633 | var value: Developer? = nil
1634 | print("Hiring \(language.description) developer ")
1635 | switch language {
1636 | case .Swift:
1637 | value = SwiftDeveloper()
1638 | case .ObjC:
1639 | value = ObjCDeveloper()
1640 | }
1641 | developers[language.description] = value
1642 | return value!
1643 | }
1644 | }
1645 | }
1646 | ```
1647 |
1648 | ### Usage
1649 |
1650 | ```swift
1651 |
1652 | var developerFactory = DeveloperFactory()
1653 | var developers = [Developer]()
1654 | developers.append(developerFactory.developer(by: .Swift))
1655 | developers.append(developerFactory.developer(by: .Swift))
1656 | developers.append(developerFactory.developer(by: .Swift))
1657 | developers.append(developerFactory.developer(by: .ObjC))
1658 | developers.append(developerFactory.developer(by: .ObjC))
1659 | developers.append(developerFactory.developer(by: .ObjC))
1660 | for developer in developers {
1661 | developer.writeCode()
1662 | }
1663 | ```
1664 |
1665 | ☔ Proxy
1666 | ------------------
1667 |
1668 | The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
1669 |
1670 | ### Example
1671 |
1672 | ```swift
1673 |
1674 | protocol Project {
1675 | func run()
1676 | }
1677 |
1678 | struct RealProject: Project {
1679 | var url: String
1680 |
1681 | func load() {
1682 | print("Loading project from url \(url) ...")
1683 | }
1684 |
1685 | init(url: String) {
1686 | self.url = url
1687 | load()
1688 | }
1689 |
1690 | func run() {
1691 | print("Running project \(url) ...")
1692 | }
1693 | }
1694 |
1695 | class ProxyProject: Project {
1696 | var url: String
1697 | var realProject: RealProject?
1698 |
1699 | func run() {
1700 | if realProject == nil {
1701 | realProject = RealProject(url: url)
1702 | }
1703 | realProject!.run()
1704 | }
1705 |
1706 | init(url: String) {
1707 | self.url = url
1708 | }
1709 | }
1710 | ```
1711 |
1712 | ### Usage
1713 |
1714 | ```swift
1715 |
1716 | var project = ProxyProject(url: "https://github.com/zsergey/realProject")
1717 | project.run()
1718 | ```
1719 |
1720 |
1721 | Info
1722 | ====
1723 |
1724 | 📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)
1725 |
1726 |
1727 | ```swift
1728 |
--------------------------------------------------------------------------------