"Learn Swift from Scratch" Study Notes (Day 63) - Cocoa Touch Design Patterns and Singleton Patterns of Applications

Original article, welcome to reprint. Please indicate: Guan Dongsheng's blog

 

What is a design pattern. Design patterns are solutions to specific problems in specific scenarios, and these solutions are summarized through repeated demonstrations and tests. In fact, in addition to software design, design patterns are also widely used in other fields, such as UI design and architectural design.

Let's introduce the singleton pattern in the design pattern in the Cocoa Touch framework.

 

singleton pattern

The role of the singleton pattern is to solve the problem of "there is only one instance in the application". In the Cocoa Touch framework, there are singleton classes such as UIApplication , NSUserDefaults , and NSNotificationCenter . In addition, although the NSFileManager and NSBundle classes belong to the Cocoa framework, they can also be used in the Cocoa Touch framework ( the singleton classes in the Cocoa framework include NSFileManager , NSWorkspace, and NSApplication , etc.).

 

Questions raised

In the life cycle of an application, sometimes only one instance of a class is needed. For example: when an iOS application starts, the state of the application is maintained by an instance of the UIApplication class. This instance represents the entire "application object", which can only be an instance, and its role is to share some resources and control in the application. Application access, and maintaining application state, etc.

 

solution

There are many solutions for the implementation of the singleton pattern. Apple provides an implementation of the singleton pattern in the official document " Using Swift with Cocoa and Objective-C ". In its simplest form the code is as follows:

class Singleton {
    static let sharedInstance = Singleton()
}

 

The above code uses static class attributes to implement the singleton mode. This class attribute is only executed once by lazy loading, even in the case of multi-threading, and it is guaranteed to be thread-safe.

If you need to do some initialization, you can use the following code with a closure form:

class Singleton {
    static let sharedInstance: Singleton = {
          let instance = Singleton()
          // initialize processing
          return instance
        }()
}

 

In addition to the implementation given by Apple's official above, there are many ways to implement the singleton mode.

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327034365&siteId=291194637