首页 > 解决方案 > swift中具有不同协议的工厂模式

问题描述

我正在尝试快速使用工厂模式,并给出我的代码

我有两个协议

protocol MyProtocol1{
    func callLoginAPI()
}

protocol MyProtocol2{
    func callPaymentAPI()
}

我有两个符合这些协议的结构

struct MyManager1: MyProtocol1{
    func callLoginAPI()
    {
        debugPrint("Inisde--MyManager1 and ready to call an Login API")
    }
}

struct MyManager2: MyProtocol2{
    func callPaymentAPI()
    {
        debugPrint("Inisde--MyManager2 and ready to call Payment API")
    }
}

我想使用工厂模式通过传递协议并返回符合该协议的结构的具体对象来创建 Manager 的实例

例子: ManagerFactory.create(MyProtocol1) --> should give me instance of MyManager1 and doing ManagerFactory.create(MyProtocol2) --> should give me instance of MyManager2

我认为这可能不起作用,因为我在运行时要求使用具体类型,所以我最终做了这样的事情

protocol IManagerFactory{
    func getMyManager1() -> MyProtocol1
    func getMyManager2() -> MyProtocol2
}

struct ManagerFactory: IManagerFactory
{
    func getMyManager1() -> MyProtocol1 {
        return MyManager1()
    }

    func getMyManager2() -> MyProtocol2 {
        return MyManager2()
    }
}

但是我很好奇我在示例中尝试做的事情是否可以实现,我使用的是 swift 4.2。

我看过其他示例,但它们都具有相同的协议,它们符合相同的协议,例如矩形、正方形和圆形符合相同的协议形状。

就我而言,我有两个独立的协议,它们做完全不同的事情,所以我在示例中尝试做的事情是否可能?或者我最终的方式是解决它的唯一方法。

请建议什么是最好的方法。

标签: iosswiftgenericsswift4.2

解决方案


建议一个快速的选择:

protocol Manager {
    // a generic protocol for all managers
}

protocol BadManager: Manager {
    // properties and behaviour of BadManager
    mutating func noBonus()
}

protocol GoodManager: Manager {
    // properties and behaviour of GoodManager
    mutating func bigBonus()
}

protocol ManagerFactory {
    associatedtype Manager
    mutating func createManager() -> Manager
}

struct gm: GoodManager {
    mutating func bigBonus() {
        print("tons of cookies & coffee")
    }
}

struct bm: BadManager {
    mutating func noBonus() {
        print("all fired")
    }
}

enum ManagerCreator<Manager>: ManagerFactory {
    func createManager() -> Manager {
        switch self {
        case .goodManager:
            return gm() as! Manager
        case .badManager:
            return bm() as! Manager
        }
    }
    case goodManager
    case badManager
}

推荐阅读