@@ -12,36 +12,32 @@ Protocols
12
12
*/
13
13
protocol Decimal {
14
14
func stringValue( ) -> String
15
+ // factory
16
+ static func make( string : String ) -> Decimal
15
17
}
16
18
17
- protocol NumberFactoryProtocol {
18
- func numberFromString( string : String ) -> Decimal
19
- }
19
+ typealias NumberFactory = ( String ) -> Decimal
20
20
21
- // Number implementations
21
+ // Number implementations with factory methods
22
22
23
23
struct NextStepNumber : Decimal {
24
24
private var nextStepNumber : NSNumber
25
25
26
26
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
+ }
27
32
}
28
33
29
34
struct SwiftNumber : Decimal {
30
35
private var swiftInt : Int
31
36
32
37
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 {
45
41
return SwiftNumber ( swiftInt: ( string as NSString ) . integerValue)
46
42
}
47
43
}
@@ -52,24 +48,23 @@ enum NumberType {
52
48
case NextStep, Swift
53
49
}
54
50
55
- class NumberAbstractFactory {
56
- class func numberFactoryType( type : NumberType ) -> NumberFactoryProtocol {
57
-
51
+ class NumberHelper {
52
+ class func factoryFor( type : NumberType ) -> NumberFactory {
58
53
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
63
58
}
64
59
}
65
60
}
66
61
/*:
67
62
### Usage
68
63
*/
69
- let factoryOne = NumberAbstractFactory . numberFactoryType ( . NextStep)
70
- let numberOne = factoryOne. numberFromString ( " 1 " )
64
+ let factoryOne = NumberHelper . factoryFor ( . NextStep)
65
+ let numberOne = factoryOne ( " 1 " )
71
66
numberOne. stringValue ( )
72
67
73
- let factoryTwo = NumberAbstractFactory . numberFactoryType ( . Swift)
74
- let numberTwo = factoryTwo. numberFromString ( " 2 " )
68
+ let factoryTwo = NumberHelper . factoryFor ( . Swift)
69
+ let numberTwo = factoryTwo ( " 2 " )
75
70
numberTwo. stringValue ( )
0 commit comments