【问题标题】:restrict creation of of objects to a factory in swift 4在swift 4中将对象的创建限制为工厂
【发布时间】:2019-02-16 03:29:28
【问题描述】:

我在 swift 4.2 中有一个类家族,我想将这些实例的创建限制在工厂类中,在 C++ 中,我可以通过将构造函数声明为私有并将friend关键字添加到工厂方法来强制执行此操作,例如这个:

class A{
 friend factoryClass::createInstance(int type);
  private A();
}

class subA: private A{
  friend factoryClass::createInstance(int type);
  private subA() : A(){
  }
}

class factoryClass{
    static A* createInstance(int type){
      switch(type){
      case 0:
         return new A();
      case 1:
      default:
         return new subA();
      }
    }
}

在 swift 4.2 中可以做到这一点吗?我对此很陌生。

【问题讨论】:

    标签: ios xcode design-patterns factory-pattern swift4.2


    【解决方案1】:

    是否可以使用fileprivate 关键字。

    https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html

    class A {
        fileprivate init() {
    
        }
    }
    
    class SubA: A {
        fileprivate override init() {
    
        }
    }
    
    class FactoryClass {
        static func createInstance(type: Int) -> A {
            switch type {
            case 0:
                return A()
            default:
                return SubA()
            }
        }
    }
    

    【讨论】:

    • 但这是否意味着我所有的类族都必须在同一个文件中声明和实现?
    猜你喜欢
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多