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中工厂模式的示例的主要内容,如果未能解决你的问题,请参考以下文章

swift Swift中桥接模式的示例

swift Swift中单例模式的示例

swift Swift中带有协议的构建器模式示例

Swift 中的设计模式 #3 外观模式与适配器模式

如何从 Swift 调用 Objective-C 类的工厂方法?

《从零开始学Swift》学习笔记(Day 52)——Cocoa错误处理模式