gpt4 book ai didi

ios - 快速使用不同协议(protocol)的工厂模式

转载 作者:行者123 更新时间:2023-11-28 07:31:39 25 4
gpt4 key购买 nike

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

我有两个协议(protocol)

protocol MyProtocol1{
func callLoginAPI()
}

protocol MyProtocol2{
func callPaymentAPI()
}

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

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")
}
}

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

示例: ManagerFactory.create(MyProtocol1) --> 应该给我 MyManager1 的实例并且执行 ManagerFactory.create(MyProtocol2) --> 应该给我 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。

我见过其他示例,但它们都具有相同的协议(protocol),它们遵循相同的协议(protocol),例如矩形、正方形和圆形遵循相同的协议(protocol)形状。

在我的例子中,我有两个独立的协议(protocol),它们做完全不同的事情,所以我在这个例子中尝试做的事情是否有可能?或者我最终采用的方式是唯一的解决方法。

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

最佳答案

首先,我非常怀疑“管理器”是一个值(一个结构)而不是一个实例(一个类)。你真的打算在这里使用结构和协议(protocol)吗?结构没有标识;具有相同属性的两个结构必须可以完全互换,而类似的东西通常不会被命名为“manager”。

你所描述的当然是可写的。这有点没用。写法如下:

struct ManagerFactory {
static func create(_ type: MyProtocol1.Protocol) -> MyProtocol1 {
return MyManager1()
}

static func create(_ type: MyProtocol2.Protocol) -> MyProtocol2 {
return MyManager2()
}
}

let mgr1 = ManagerFactory.create(MyProtocol1.self)
let mgr2 = ManagerFactory.create(MyProtocol2.self)

但这只是使用方法重载替换名称的一种精心设计的方法。

你似乎想要的是一个单一的方法,但它的返回类型是什么?即使在 C# 中,如果不添加令人讨厌的向下转换,我也不认为这是可写的。 (这是您和 paulw11 在评论中讨论的重点。)这不是 Swift 的限制;这是类型的基本特征。即使在 JavaScript 中,您也需要知道您期望返回什么,否则您将不知道可以调用哪些方法(只是您在头脑和文档中而不是在编译器和代码中跟踪这种期望) .

您似乎在这里创建了很多协议(protocol),我敢打赌它们大多只有一个实现。那是糟糕的 swift 。除非您有特定需求,否则不要创建协议(protocol)。不要为了好玩而创造景点。他们会很快烧死你。

如果您的协议(protocol)确实看起来像这样,并且您真的对这些方法有不同的实现(即,如果只有一个 MyProtocol1 实现,请不要这样做”以防万一”),你真正想要的是函数:

struct API {
let login: () -> Void
let payment: () -> Void
}

let myAPI = API(login: myLoginFunction, payment: myPaymentFunction)

这将允许您在需要时创建不同的 API。但同样,只有当您需要这种灵 active 时。如果没有,只需对实例使用类,对值使用结构,并避免使用协议(protocol),直到您的程序中至少有 2 个,最好是 3 个实现。

关于ios - 快速使用不同协议(protocol)的工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com