Complex hierarchy problem in Objective-c
I don't know if it is so complex like I say :P
This is the case use: I have a project with a lot of targets, and all use the same common code, but I create children class to use specific things. This is the spirit of object-oriented.
I have this hierarchy in program
NSObject -> ClassA_level_1 -> ClassA_level_2
NSObject -> ClassB_level_1 -> ClassB_level_2
ClassB_level_1 have a variable ClassA_level_1 *classA
so call function in level1 is no problem. The problem is that ClassB_level_1 have to call things in ClassA_level_2 (NOT level 1) in some delegates function.
If in level_2 i can call super to g开发者_StackOverflow社区et things in level_1, how can I do the opposite way? There are some tricky?
When you encounter this problem, you are most likely violating Liskov's Substitution Principle. In OOP, a square is not a rectangle.
If you are not violating LSP, then ClassB_level_1
should still not be calling anything in ClassA_level_2
. ClassB_level_2
should be where that special logic is implemented, and it should therefore know the class of its delegate, and be able to assert that the class is correct and then cast to it. That said, if you find yourself here, it's often because of a more basic architectural problem.
First, reconsider your problem in terms of protocols rather than classes. What functionality do you really need from this other object? Check it with a protocol and respondsToSelector:
rather than by asserting some class.
Could ClassB
be a factory for ClassA
so that it always creates the correct helper object? Perhaps you should reconsider this as a Class Cluster. When you find yourself creating complicated parallel hierarchies, often it's time to pull out Design Patterns and rethink your architecture. In particular, Decorator is often useful for problems that would otherwise lead to large parallel trees.
But if your design is correct, you just need to use respondsToSelector:
to make sure your delegate responds to the method you want before calling it.
精彩评论