swift设计模式-工厂模式

/*:
 Factory Method
-----------------

 工厂模式是用来取代类构造函数,抽象对象的生成过程,对象实例化的类型可以在运行时决定的。
 
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.

### Example
*/
protocol Currency {
    func symbol() -> String
    func code() -> String
}

class Euro : Currency {
    func symbol() -> String {
        return "€"
    }
    
    func code() -> String {
        return "EUR"
    }
}

class UnitedStatesDolar : Currency {
    func symbol() -> String {
        return "$"
    }
    
    func code() -> String {
        return "USD"
    }
}

enum Country {
    case UnitedStates, Spain, UK, Greece
}

enum CurrencyFactory {
    static func currencyForCountry(country:Country) -> Currency? {

        switch country {
            case .Spain, .Greece :
                return Euro()
            case .UnitedStates :
                return UnitedStatesDolar()
            default:
                return nil
        }
        
    }
}
/*:
### Usage
*/
let noCurrencyCode = "No Currency Code Available"

CurrencyFactory.currencyForCountry(.Greece)?.code() ?? noCurrencyCode
CurrencyFactory.currencyForCountry(.Spain)?.code() ?? noCurrencyCode
CurrencyFactory.currencyForCountry(.UnitedStates)?.code() ?? noCurrencyCode
CurrencyFactory.currencyForCountry(.UK)?.code() ?? noCurrencyCode

你可能感兴趣的:(swift设计模式-工厂模式)