C++: Recommendations for Member Function Access at the Same Architecture Layer
I have 4 classes of the following hierachy:
MyTop
|
-------------------
| | |
BlockA BlockB BlockC
BlockA
, BlockB
, and BlockC
are the composed objects of MyTop
. BlockA
provides a function LookUpTable()
, and BlockB
and BlockC
now need to access the look-up table owned by BlockA
. What is a goo开发者_高级运维d (or at least typical) practice for BlockB
and BlockC
to access the look-up table?
I thought about implementing the look-up table as a class itself, but the content of the loop-up table is slightly coupled with the initialization of BlockA
, and it may not be trivial to decouple the table from BlockA
(it's still doable, but not preferred). Right now my solution is to pass the request from BlockB
and BlockC
to MyTop
, and let MyTop
to manage the communication between the blocks. However, it doesn't seem a good way to handle the problem when there are more blocks that need access to the look-up table in BlockA
. I wonder if this is a well-known problem and already has a "best practice" solution to it. Thanks!
I thought about implementing the look-up table as a class itself, but the content of the loop-up table is slightly coupled with the initialization of BlockA, and it may not be trivial to decouple the table from BlockA (it's still doable, but not preferred).
Can't you simply make BlocA intialize that look-up table owner object? It would be a singleton (if it's correct in your case) with BlocA as friend class to be sure it's the only one to access initialization (construction?) functions.
I don't know if there's a general solution but there definitely is a general advice: tell, don't ask.
From what I can see you are trying to access the data of BlockA
that is stored in a lookup table and then perform some operation on them. This is violation of the encapsulation principle where only the object holding the data should access and modify it.
A better way would be to extract the lookup table functionality into a class and add common methods for all three blocks. Then create three subclasses of the lookup table class and add methods that will be used only by specific blocks (if there are any such methods). In BlockA
, BlockB
and BlockC
use these classes. This allows a more loose coupling than accessing a lookup table stored directly in BlockA
.
With the current mechanism, BlockB and BlockC consumes the facility provided in BlockA. My understanding is that it makes it different from BlockA. They are not on par.
BlockA, BlockB, BlockC inherits the methods of MyTop.
- So LookUpTable() a method of MyTop.
- It should access a object attribute which is initialized only when you instantiate BlockA.
精彩评论