Custom class clusters in Swift

前端 未结 7 2006
灰色年华
灰色年华 2020-12-02 00:04

This is a relatively common design pattern:

https://stackoverflow.com/a/17015041/743957

It allows you to return a subclass from your init calls.

7条回答
  •  死守一世寂寞
    2020-12-02 00:27

    protocol SomeProtocol {
       init(someData: Int)
       func doSomething()
    }
    
    class SomeClass: SomeProtocol {
    
       var instance: SomeProtocol
    
       init(someData: Int) {
          if someData == 0 {
             instance = SomeOtherClass()
          } else {
             instance = SomethingElseClass()
          }
       }
    
       func doSomething() {
          instance.doSomething()
       }
    }
    
    class SomeOtherClass: SomeProtocol {
       func doSomething() {
          print("something")
       }
    }
    
    class SomethingElseClass: SomeProtocol {
       func doSomething() {
         print("something else")
       }
    }
    

    Basically you create a protocol that your class cluster inherits from. You then wrap around an instance variable of the same type and choose which implementation to use.

    For example, if you were writing an array class that switched between a LinkedList or a raw array then SomeOtherClass and SomethingElseClass might be named LinkedListImplementation or PlainArrayImplementation and you could decide which one to instantiate or switch to based on whatever is more efficient.

提交回复
热议问题