-1

I have 4 classes(C1, C2, C3, C4) that use class M1. M1 holds the model and all the data. M1 may be instantiated by any of the Cx classes if it is not already. If it is, then I don't want to create another instance of it, just get the pointer to an instance of M1 in existence, so the data can be used there.

How can I do this? Is there a way to search for an instance of the class?

jscs
  • 63,694
  • 13
  • 151
  • 195
jdl
  • 6,151
  • 19
  • 83
  • 132
  • 2
    C++ or ObjC? They're not the same. – Barmar Feb 04 '16 at 02:38
  • I had done this before in C++, but don't remember how. I am programming in Objective-c, but think c++ code would work as well... either way... – jdl Feb 04 '16 at 03:27

2 Answers2

0

This looks like the Factory Pattern, where you define an additional MFactory class, that holds a pointer to M, and a getter method M* getM(). When the Cx classes need the M instance, they query MFactory for that instance using getM(). The instance then is created, if it hasn't been already. What this design may miss is to allow only Cx classes to query MFactory, but from the description I conclude that this is not a hard requirement here.

Another issue is how to define which Cx classes use which M instance, thus, which exact factory object they query. This factory class may be a singleton, but then all the Cx class sets are going to share the same model (which is probably not your intent). OR, each set may share one model (and thus one MFactory). One more possible implementation is to have a factory create the whole Cx set and initialize it with the same model object, and make sure that Cx are created only via that factory.

iksemyonov
  • 4,106
  • 1
  • 22
  • 42
0

This is the behavior of the standard Cocoa (pseudo-)singleton implementation:

+ (instancetype)sharedInstance
{
    static id sharedInstance;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

Have the Cn classes access M1 only through this class method and you will always be using the same instance.

Other classes can still create their own instances of M1 in the usual way, with +alloc or +new. (That's why this is a pseudo-singleton.)

This shared access doesn't have to be part of M1's public interface, either. You could just as easily put this into a category method that's only visible to the Cn classes.

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195