限制在swift 4中创建对象到工厂

问题描述 投票:0回答:1

我在swift 4.2中有一系列类,我想将这些实例的创建仅限于工厂类,在C ++中我可以通过将构造函数声明为private来强制执行此操作,并将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个回答
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()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.