[英]Factory pattern with different protocols in 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
}
首先,我非常懷疑“管理器”是值(結構)而不是實例(類)。 您真的是真的要在這里使用結構和協議嗎? 結構沒有身份; 具有相同屬性的兩個結構必須彼此完全可互換,並且類似的事情通常不會被命名為“ 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的局限;它只是對Swift的限制。 這是類型的基本特征。 即使在JavaScript中,您也需要知道期望返回的內容,否則您將不知道可以調用哪種方法(只是在您的頭腦和文檔中而不是在編譯器和代碼中跟蹤期望) 。
您似乎在這里創建了很多協議,我敢打賭,它們大多數都只有一個實現。 那太糟糕了,斯威夫特。 在有特定需求之前不要創建協議。 不要創造有趣的景點。 他們會很快燒死你。
如果您的協議確實看起來像這樣,並且您對這些方法確實有不同的實現(即,如果只有MyProtocol1
一種實現“以防萬一”, MyProtocol1
),那么您真正想要的是函數:
struct API {
let login: () -> Void
let payment: () -> Void
}
let myAPI = API(login: myLoginFunction, payment: myPaymentFunction)
如果需要,這將使您創建不同的API。 但是同樣,僅當您需要這種靈活性時。 如果不是這樣,則僅將類用於實例,將結構用於值,並避免使用協議,直到程序中至少有2個(最好是3個)實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.