Passing an object between many classes with the smallest possible join

In my application, I use a class (which is now single), called ClassA for example, to manage files.

Since this is a singleton, I used this behavior to get this unique instance in many classes that it needs.

But now I can no longer keep this class as a singleton, I need to have one instance of NSDocument.

So, I created an instance of the ClassA class in my subclass of NSDocument, but the problem is passing this object to the classes that it needs.

I have this structure:

Class1 <- Class2 <- Class3 <- Document โ†’ ClassA

I need to have access to an instance of ClassA document in Class1.

I can use Dependency Injection to pass ClassA to Class1 using init or setter methods, but since the Document does not have direct access to Class1, I need to pass it to Class3, then Class2 and Class1.

Is this the only way to do this? Or is there another better way to handle this?

+4
source share
1 answer

I would say, back to your singleton principle, but using NSDocument as the key in the ClassA object ClassA ; sort of:

 static NSMutableDictionary *_classCache = [[NSMutableDictionary alloc] init]; + (ClassA *)classAForDocument:(NSDocument *)document { ClassA *classA = [_classCache objectForKey:document]; if (classA == nil) { // Initialise with something specific to the document I guess... classA = [[ClassA alloc] init]; [_classCache setObject:classA forKey:document]; } return classA; } 

This requires that Class{1,2,3} know the document to which they belong.

+1
source

All Articles