swift Swift中工厂模式的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift中工厂模式的示例相关的知识,希望对你有一定的参考价值。

//Factory Pattern (Creational)
//Allows logic of which type will be created to be handled by a method

protocol SimpleType {
    var simpleName: String { get }
}

struct Type1: SimpleType {
    var simpleName: String = "Type1"
}

struct Type2: SimpleType {
    var simpleName: String = "Type2"
}

/* 
 Factory Method
 Handles logic of which specific struct to return
 */
func simpleTypeFactory(getType type: Int) -> SimpleType? {
    switch type {
    case 1:
        return Type1()
    case 2:
        return Type2()
    default:
        return nil
    }
}

let type1 = simpleTypeFactory(getType: 1)
type1?.dynamicType //Type1
type1?.simpleName  //"Type1"

以上是关于swift Swift中工厂模式的示例的主要内容,如果未能解决你的问题,请参考以下文章