TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | MIT |
ReleasedLast Release | May 2016 |
Maintained by Alexey Belkevich.
Multiton is a better alternative to singleton. It's more flexible and require less code lines to implement.
Features:
ABMultitonProtocol
to class interface. No implementation needed!init
method with arguments.shared
.Warning
This is not implementation of classic multiton. This implementation uses instance
class name
askey
to access instance.
Add to Podfile
pod 'ABMultiton'
Class should conforms to ABMultitonProtocol
#import "ABMultitonProtocol.h"
...
@interface MyClass : ParentClass <ABMultitonProtocol>
...
@end
And 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