-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathContents.swift
More file actions
73 lines (56 loc) · 1.5 KB
/
Contents.swift
File metadata and controls
73 lines (56 loc) · 1.5 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 协议
protocol Operator {
var nums: (Double, Double) { get set }
func getResult() -> Double?
// 工厂
static func createOperation() -> Operator
}
// 遵守协议
struct Addition: Operator {
static func createOperation() -> Operator {
return Addition()
}
var nums = (0.0, 0.0)
func getResult() -> Double? {
return nums.0 + nums.1
}
}
struct Subtraction: Operator {
static func createOperation() -> Operator {
return Subtraction()
}
var nums = (0.0, 0.0)
func getResult() -> Double? {
return nums.0 - nums.1
}
}
struct Multiplication: Operator {
static func createOperation() -> Operator {
return Multiplication()
}
var nums = (0.0, 0.0)
func getResult() -> Double? {
return nums.0 * nums.1
}
}
struct Division: Operator {
static func createOperation() -> Operator {
return Division()
}
var nums = (0.0, 0.0)
func getResult() -> Double? {
guard nums.1 != 0 else {
return nil
}
return nums.0 / nums.1
}
}
var testAddition = Addition.createOperation()
testAddition.nums = (2, 3)
print(testAddition.getResult() ?? "Error")
var testDivision = Division.createOperation()
testDivision.nums = (2, 0)
print(testDivision.getResult() ?? "Error")