Multiton is a better alternative to singleton. It's more flexible and require less code lines to implement.
Features:
- Make shared instance of class just by including
ABMultitonProtocolto class interface. No implementation needed! - Remove shared instance of class when you don't need it anymore (unit-tests!). No more immortal instances!
- Specify is shared instance should be removed on memory warning.
- Create shared instance with custom
initmethod with arguments. - Set custom instance that will return as
shared.
Warning
This is not implementation of classic multiton. This implementation uses instance
class nameaskeyto access instance.
Add to Podfile
pod 'ABMultiton'
Class should conforms to ABMultitonProtocol
#import "ABMultitonProtocol.h"
...
@interface MyClass : ParentClass <ABMultitonProtocol>
...
@endAnd that's all! ABMultiton will add shared method implementation in runtime. And you can access shared instance just like this:
[MyClass.shared myMethod];ABMultiton implements shared method in this way
return [[MyClass alloc] init];And if you need to use some custom init method you should implement shared method by yourself in this way:
#import "ABMultiton.h"
...
+ (instancetype)shared
{
return [ABMultiton sharedInstanceOfClass:self.class withInitBlock:^id
{
MyClass *instance = [[MyClass alloc] initWithArgument:value];
instance.someProperty = propertyValue;
return instance;
}];
}It's very useful in unit tests. So, if you don't need shared instance you can remove it by this call:
[MyClass removeShared];This method is also injected by ABMultiton in runtime. Here is method implementation:
[ABMultiton removeInstanceOfClass:MyClass.class];Sometimes you don't need shared instance for all app life cycle. And you may want to release some shared instances on low memory. It's pretty easy. Just implement optional method isRemovableInstance of ABMultitonProtocol
@implementation MyClass
...
- (BOOL)isRemovableInstance
{
return YES;
}And this instance will be released on memory warning. Or you can release all such instances manually by this call:
[ABMultiton purgeRemovableInstances];BOOL isExists = [ABMultiton containsInstanceOfClass:[MyClass class]];Using ABMultiton is thread safe.
Please, don't create shared instance for class if you can. "Singleton mania" is a well known anti-pattern.
ABMultiton contain subspec SetInstance. It's allow to replace or add instance for class that will return on shared method call. It can be very useful with unit-tests.
Replace pod 'ABMultiton' with pod 'ABMultiton/SetInstance'
[ABMultiton setInstance:customInstance forClass:MyClass.class];Stay tuned with ABMultiton updates at @okolodev
