GULCCComponentContainer.m 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "Public/GULCCComponentContainer.h"
  17. #import "Public/GULCCComponent.h"
  18. #import "Public/GULCCLibrary.h"
  19. #import <GoogleUtilities/GULLogger.h>
  20. static GULLoggerService kGULComponentContainer = @"[GoogleUtilitiesComponents]";
  21. NS_ASSUME_NONNULL_BEGIN
  22. @interface GULCCComponentContainer ()
  23. /// The dictionary of components that are registered for a particular app. The key is an `NSString`
  24. /// of the protocol.
  25. @property(nonatomic, strong)
  26. NSMutableDictionary<NSString *, GULCCComponentCreationBlock> *components;
  27. /// Cached instances of components that requested to be cached.
  28. @property(nonatomic, strong) NSMutableDictionary<NSString *, id> *cachedInstances;
  29. /// Protocols of components that have requested to be eagerly instantiated.
  30. @property(nonatomic, strong, nullable) NSMutableArray<Protocol *> *eagerProtocolsToInstantiate;
  31. @end
  32. @implementation GULCCComponentContainer
  33. // Collection of all classes that register to provide components.
  34. static NSMutableSet<Class> *sGULComponentRegistrants;
  35. #pragma mark - Public Registration
  36. + (void)registerAsComponentRegistrant:(Class<GULCCLibrary>)klass {
  37. static dispatch_once_t onceToken;
  38. dispatch_once(&onceToken, ^{
  39. sGULComponentRegistrants = [[NSMutableSet<Class> alloc] init];
  40. });
  41. [self registerAsComponentRegistrant:klass inSet:sGULComponentRegistrants];
  42. }
  43. + (void)registerAsComponentRegistrant:(Class<GULCCLibrary>)klass
  44. inSet:(NSMutableSet<Class> *)allRegistrants {
  45. [allRegistrants addObject:klass];
  46. }
  47. #pragma mark - Internal Initialization
  48. - (instancetype)initWithContext:(nullable id)context {
  49. return [self initWithContext:context registrants:sGULComponentRegistrants];
  50. }
  51. - (instancetype)initWithContext:(nullable id)context
  52. registrants:(NSMutableSet<Class> *)allRegistrants {
  53. self = [super init];
  54. if (self) {
  55. _context = context;
  56. _cachedInstances = [NSMutableDictionary<NSString *, id> dictionary];
  57. _components = [NSMutableDictionary<NSString *, GULCCComponentCreationBlock> dictionary];
  58. [self populateComponentsFromRegisteredClasses:allRegistrants withContext:context];
  59. }
  60. return self;
  61. }
  62. - (void)populateComponentsFromRegisteredClasses:(NSSet<Class> *)classes withContext:(id)context {
  63. // Keep track of any components that need to eagerly instantiate after all components are added.
  64. self.eagerProtocolsToInstantiate = [[NSMutableArray alloc] init];
  65. // Loop through the verified component registrants and populate the components array.
  66. for (Class<GULCCLibrary> klass in classes) {
  67. // Loop through all the components being registered and store them as appropriate.
  68. // Classes which do not provide functionality should use a dummy GULCCComponentRegistrant
  69. // protocol.
  70. for (GULCCComponent *component in [klass componentsToRegister]) {
  71. // Check if the component has been registered before, and error out if so.
  72. NSString *protocolName = NSStringFromProtocol(component.protocol);
  73. if (self.components[protocolName]) {
  74. GULLogError(kGULComponentContainer, NO, @"I-COM000001",
  75. @"Attempted to register protocol %@, but it already has an implementation.",
  76. protocolName);
  77. continue;
  78. }
  79. // Store the creation block for later usage.
  80. self.components[protocolName] = component.creationBlock;
  81. // Queue any protocols that should be eagerly instantiated. Don't instantiate them yet
  82. // because they could depend on other components that haven't been added to the components
  83. // array yet.
  84. if (component.instantiationTiming == GULCCInstantiationTimingAlwaysEager) {
  85. [self.eagerProtocolsToInstantiate addObject:component.protocol];
  86. }
  87. }
  88. }
  89. }
  90. #pragma mark - Instance Creation
  91. - (void)instantiateEagerComponents {
  92. // After all components are registered, instantiate the ones that are requesting eager
  93. // instantiation.
  94. @synchronized(self) {
  95. for (Protocol *protocol in self.eagerProtocolsToInstantiate) {
  96. // Get an instance for the protocol, which will instantiate it since it couldn't have been
  97. // cached yet. Ignore the instance coming back since we don't need it.
  98. __unused id unusedInstance = [self instanceForProtocol:protocol];
  99. }
  100. // All eager instantiation is complete, clear the stored property now.
  101. self.eagerProtocolsToInstantiate = nil;
  102. }
  103. }
  104. /// Instantiate an instance of a class that conforms to the specified protocol.
  105. /// This will:
  106. /// - Call the block to create an instance if possible,
  107. /// - Validate that the instance returned conforms to the protocol it claims to,
  108. /// - Cache the instance if the block requests it
  109. ///
  110. /// Note that this method assumes the caller already has @sychronized on self.
  111. - (nullable id)instantiateInstanceForProtocol:(Protocol *)protocol
  112. withBlock:(GULCCComponentCreationBlock)creationBlock {
  113. if (!creationBlock) {
  114. return nil;
  115. }
  116. // Create an instance using the creation block.
  117. BOOL shouldCache = NO;
  118. id instance = creationBlock(self, &shouldCache);
  119. if (!instance) {
  120. return nil;
  121. }
  122. // An instance was created, validate that it conforms to the protocol it claims to.
  123. NSString *protocolName = NSStringFromProtocol(protocol);
  124. if (![instance conformsToProtocol:protocol]) {
  125. GULLogError(kGULComponentContainer, NO, @"I-COM000002",
  126. @"An instance conforming to %@ was requested, but the instance provided does not "
  127. @"conform to the protocol",
  128. protocolName);
  129. }
  130. // The instance is ready to be returned, but check if it should be cached first before returning.
  131. if (shouldCache) {
  132. self.cachedInstances[protocolName] = instance;
  133. }
  134. return instance;
  135. }
  136. #pragma mark - Internal Retrieval
  137. - (nullable id)instanceForProtocol:(Protocol *)protocol {
  138. // Check if there is a cached instance, and return it if so.
  139. NSString *protocolName = NSStringFromProtocol(protocol);
  140. id cachedInstance;
  141. @synchronized(self) {
  142. cachedInstance = self.cachedInstances[protocolName];
  143. if (!cachedInstance) {
  144. // Use the creation block to instantiate an instance and return it.
  145. GULCCComponentCreationBlock creationBlock = self.components[protocolName];
  146. cachedInstance = [self instantiateInstanceForProtocol:protocol withBlock:creationBlock];
  147. }
  148. }
  149. return cachedInstance;
  150. }
  151. #pragma mark - Lifecycle
  152. - (void)removeAllCachedInstances {
  153. @synchronized(self) {
  154. // Loop through the cache and notify each instance that is a maintainer to clean up after
  155. // itself.
  156. for (id instance in self.cachedInstances.allValues) {
  157. if ([instance conformsToProtocol:@protocol(GULCCComponentLifecycleMaintainer)] &&
  158. [instance respondsToSelector:@selector(containerWillBeEmptied:)]) {
  159. [instance containerWillBeEmptied:self];
  160. }
  161. }
  162. // Empty the cache.
  163. [self.cachedInstances removeAllObjects];
  164. }
  165. }
  166. @end
  167. NS_ASSUME_NONNULL_END