Skip to content

Commit a3f5018

Browse files
committed
Merge pull request ochococo#42 from erykwarren/master
Suggestion for AbstractFactory using typealias to define factory type
2 parents 35ed618 + 31f596d commit a3f5018

File tree

1 file changed

+22
-27
lines changed

1 file changed

+22
-27
lines changed

source/creational/abstract_factory.swift

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -12,36 +12,32 @@ Protocols
1212
*/
1313
protocol Decimal {
1414
func stringValue() -> String
15+
// factory
16+
static func make(string : String) -> Decimal
1517
}
1618

17-
protocol NumberFactoryProtocol {
18-
func numberFromString(string : String) -> Decimal
19-
}
19+
typealias NumberFactory = (String) -> Decimal
2020

21-
// Number implementations
21+
// Number implementations with factory methods
2222

2323
struct NextStepNumber : Decimal {
2424
private var nextStepNumber : NSNumber
2525

2626
func stringValue() -> String { return nextStepNumber.stringValue }
27+
28+
// factory
29+
static func make(string : String) -> Decimal {
30+
return NextStepNumber(nextStepNumber:NSNumber(longLong:(string as NSString).longLongValue))
31+
}
2732
}
2833

2934
struct SwiftNumber : Decimal {
3035
private var swiftInt : Int
3136

3237
func stringValue() -> String { return "\(swiftInt)" }
33-
}
34-
/*:
35-
Factories
36-
*/
37-
class NextStepNumberFactory : NumberFactoryProtocol {
38-
func numberFromString(string : String) -> Decimal {
39-
return NextStepNumber(nextStepNumber:NSNumber(longLong:(string as NSString).longLongValue))
40-
}
41-
}
42-
43-
class SwiftNumberFactory : NumberFactoryProtocol {
44-
func numberFromString(string : String) -> Decimal {
38+
39+
// factory
40+
static func make(string : String) -> Decimal {
4541
return SwiftNumber(swiftInt:(string as NSString).integerValue)
4642
}
4743
}
@@ -52,24 +48,23 @@ enum NumberType {
5248
case NextStep, Swift
5349
}
5450

55-
class NumberAbstractFactory {
56-
class func numberFactoryType(type : NumberType) -> NumberFactoryProtocol {
57-
51+
class NumberHelper {
52+
class func factoryFor(type : NumberType) -> NumberFactory {
5853
switch type {
59-
case .NextStep:
60-
return NextStepNumberFactory()
61-
case .Swift:
62-
return SwiftNumberFactory()
54+
case .NextStep:
55+
return NextStepNumber.make
56+
case .Swift:
57+
return SwiftNumber.make
6358
}
6459
}
6560
}
6661
/*:
6762
### Usage
6863
*/
69-
let factoryOne = NumberAbstractFactory.numberFactoryType(.NextStep)
70-
let numberOne = factoryOne.numberFromString("1")
64+
let factoryOne = NumberHelper.factoryFor(.NextStep)
65+
let numberOne = factoryOne("1")
7166
numberOne.stringValue()
7267

73-
let factoryTwo = NumberAbstractFactory.numberFactoryType(.Swift)
74-
let numberTwo = factoryTwo.numberFromString("2")
68+
let factoryTwo = NumberHelper.factoryFor(.Swift)
69+
let numberTwo = factoryTwo("2")
7570
numberTwo.stringValue()

0 commit comments

Comments
 (0)