【问题标题】:How do I implement this protocol in struct如何在 struct 中实现此协议
【发布时间】:2016-04-25 09:33:53
【问题描述】:

我是 Swift 新手,我想为数据库访问创建一个抽象工厂。 这是我的协议

protocol IDAOFactory
{
  associatedtype DAO: IDAO

  func createAccountDAO<DAO: IAccountDAO>() -> DAO
}

struct RealmFactory: IDAOFactory
{

}

protocol IDAO
{
   associatedtype T
   func save(object: T)
}

protocol IAccountDAO : IDAO
{

}

struct AccountDAORealm: IAccountDAO
{

}

struct RealmFactory 中的 IDAOFactory 和 struct AccountDAORealm 中的 IAccountDAO 如何实现? 有人可以帮忙吗?

【问题讨论】:

  • 为什么是结构?结构是值对象,而不是引用对象。
  • 你的意思是使用Class会更好?
  • 这是你的决定,但结构是作为 传递的,所以每个调用你的工厂的人都会得到不同的结构。每次将结构传递给函数时,都会创建该结构的副本。
  • 另外,如果你以后需要,你将无法继承结构。
  • 感谢您的建议

标签: swift design-patterns protocols abstract-factory


【解决方案1】:

Swift 中的泛型有很多限制,尤其是在协议中使用和在结构中实现时。让我们等到 Swift 3 :)

我使用协议和派生类或泛型与类,但在 Swift 2 中混合使用协议泛型和结构会让人头疼(C# 泛型更方便)

我在操场上玩过你的代码,在这里

protocol IDAOFactory
{
    associatedtype DAO: IDAO

    func createAccountDAO<DAO: IAccountDAO>() -> DAO
}

protocol IDAO
{
    init()
    associatedtype T
    func save(object: T)
}

protocol IAccountDAO : IDAO
{
    init()
}

public class AccountDAORealm: IAccountDAO
{
    var data: String = ""

    required public init() {
        data = "data"
    }

    func save(object: AccountDAORealm) {
        //do save
    }
}

let accountDAORealm = AccountDAORealm() 
//As you see accountDAORealm is constructed without any error

struct RealmFactory: IDAOFactory
{
    func createAccountDAO<AccountDAORealm>() -> AccountDAORealm {
        return  AccountDAORealm() //but here constructor gives error
    }
}

【讨论】:

  • 似乎在课堂上实现会是一个更好的方法。它是一个令人头疼的快速语法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 2013-07-01
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 2011-08-18
相关资源
最近更新 更多