設計模式 Swift(簡單工廠)

閱讀大話設計模式心得,使用 Swift Ver. 3.0 (Jun 6, 2016)

Swift API Doc

簡單計算機程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let numA        = 10
let numB = 20
var resultNum = 0
let strOperate = "+"

switch(strOperate){
case "+":
resultNum = numA + numB
case "-":
resultNum = numA - numB
case "*":
resultNum = numA * numB
case "/":
if numB != 0 {
resultNum = numA / numB
} else {
print("Error")
}
default:
print("default")
}
print("Result = \(resultNum)")

物件導向程式

希望程式 1.可維護 2.可複用 3.可擴展 4.靈活性好

=> 透過程式重構、封裝、繼承、多型、降低偶合度

功能封裝

把業務邏輯(實際計算過程)和介面邏輯(GUI等顯示畫面)分開

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
/* 使用封裝特性
業務邏輯 -> 計算類別,此類別可重複使用 */
class Operator {
class func GetResult(_ numA:Int,_ numB:Int,_ strOperate:String) -> Int {
var resultNum = 0
switch(strOperate){
case "+":
resultNum = numA + numB
case "-":
resultNum = numA - numB
case "*":
resultNum = numA * numB
case "/":
if numB != 0 {
resultNum = numA / numB
} else {
print("Error")
}
default:
print("default")
}
return resultNum
}
}

let numA = 10
let numB = 20
let strOperate = "+"
print("Result = \(Operator.GetResult(numA,numB,strOperate))")

耦合度

新加功能 : 要加上 sqrt 開根號功能
一般想法 : 直接在 switch 中加一個新的判斷
產生問題 :
1.程式碼要整個重新編譯(+-/),即使 +-/ 沒有更動
2.有可能修改到原有+-*/的程式碼,導致程式出錯

class Operation {
    private var _numA = 0
    private var _numB = 0

    var NumA: Int 
    {
        get { return _numA      }
        set { _numA = newValue  }
    }

    var NumB: Int 
    {
        get { return _numB      }
        set { _numB = newValue  }
    }    

    func GetResult() -> Int {
        let resultNum = 0
        return resultNum
    }
}

class OperationAdd : Operation {
    override func GetResult() -> Int { return NumA + NumB }
}

class OperationSub : Operation {
    override func GetResult() -> Int { return NumA - NumB }
}

class OperationMul : Operation {
    override func GetResult() -> Int { return NumA * NumB }
}

class OperationDiv : Operation {
    override func GetResult() -> Int { return NumA / NumB }
}