ios - 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。
我看过其他示例,但它们都具有相同的协议,它们符合相同的协议,例如矩形、正方形和圆形符合相同的协议形状。
就我而言,我有两个独立的协议,它们做完全不同的事情,所以我在示例中尝试做的事情是否可能?或者我最终的方式是解决它的唯一方法。
请建议什么是最好的方法。
解决方案
建议一个快速的选择:
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
}
推荐阅读
- java - React-native android bridge 请求许可
- firebase - 关于不安全规则的 Firebase Firestore 电子邮件
- elasticsearch - 是否可以在现有条款之上添加条款“必须”
- python - 使用最小和最大范围的时间戳绘制 ax.axhline
- mysql - 似乎解决了,但为什么呢?当通过一些 SSH 会话连接到远程 mysql 时,它总是在大约 5 分钟 ~ 10 分钟空闲时失去连接
- javascript - 如何在javascript中循环迭代两个级别的JSON对象
- node.js - 如何从现有集合 MongoDB 中获取模式
- java - JNA 将数组引用传递到本机 DLL
- python - 如何在 Python 中将 XML 内容传递给 Pandas
- javascript - 错误中心模式 Slick.js 在四个中心幻灯片中添加不透明度