Cocoa Singleton and Protocols

I want to define a protocol and create a simple, standard way to capture the "default", a common implementation of the specified protocol - singleton style. Cocoa stick to the following pattern:

[NSUserDefaults standardUserDefaults] [NSNotificationCenter defaultCenter] 

but in both cases they have @interfaces at the bottom of the object hierarchy. I am afraid how to do this using @protocols. I obviously can create a class that has empty or simple method implementations, but actually I want @protocol at the bottom of the hierarchy. I tried something like:

 @protocol ConfigurationManager <NSObject> //... @interface ConfigurationManagerFactory : NSObject + (id<ConfigurationManager>)sharedConfiguration; @end // ... id<ConfigurationManger> config = [ConfigurationManagerFactory sharedConfiguration]; [config ...]; 

and it works, but I always have to explain how to use it and why I did it this way. Is there a way to conform to Cocoa syntax (calling convention) while using the @protocols value?

Aside, is there a reason why I would not want to use @protocols like this? When implementing @interface, you can still use categories and alternative implementations, etc. - just like instantiating NSString usually leaves you with a class extending NSString.

+4
source share
2 answers

Here is the idea: create your protocol and class with the same name using the factory method, which will return the default protocol implementation to you:

 @protocol ConfigurationManager <NSObject> ... @interface ConfigurationManager : NSObject <ConfigurationManager> +(ConfigurationManager *) defaultConfigurationManager; ... 

Other specialized implementations can then inherit from your base class.

+1
source

The whole point of the protocol is that it indicates an interface without providing an implementation. If you want to implement the default, specify the class that implements your protocol, just as the NSObject class implements the NSObject protocol. Clients can then either subclass the class you provide, or instantiate the class you provide, and use the resulting implementation of the object, just like your config object.

+2
source

Source: https://habr.com/ru/post/1390901/


All Articles