美文网首页
swift设计模式-工厂模式

swift设计模式-工厂模式

作者: 刘书亚的天堂之路 | 来源:发表于2016-11-02 15:47 被阅读71次
    /*:
    🏭 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设计模式-工厂模式

          本文链接:https://www.haomeiwen.com/subject/cowvuttx.html