I have a 2 child classes that inherit from 'MyClass' and each child class should be a singleton.
I've used this pattern for getting a static instance when I don't have any other classes inheriting:
+ (MyClass *)getInstance
{
static dispatch_once_t once;
static MyClass *instance;
dispatch_once(&once, ^{
instance = [[MyClass alloc] init];
});
return instance;
}
This works just great. Now, if I add two new child classes, FirstClass and SecondClass, both of which inherit from MyClass, how do I ensure that I get back the respective ChildClass?
dispatch_once(&once, ^{
// No longer referencing 'MyClass' and instead the correct instance type
instance = [[[self class] alloc] init];
});
FirstClass *firstClass = [FirstClass getInstance]; // should be of FirstClass type
SecondClass *secondClass = [SecondClass getInstance]; // should be of SecondClass type
Doing the above means that I always get back whatever class I instantiated 1st as my second class type:
first: <FirstClass: 0x884b720>
second: <FirstClass: 0x884b720>
// Note that the address and type as identical for both.
What's the best way to create the respective child class singletons without adding getInstance
method to each of the child classes?