I have two classes. "System" and "Bluetooth". I want to have a really loose coherency between these two classes as they should be able to exist or not without depending on each other's existence.
system class should be able to notify the Bluetooth class when data is available to be sent by Bluetooth and vice versa, the Bluetooth class should be able to notify the System class when a data is received by Bluetooth and is ready to be read;
so first I came up with an idea to implement it using observer design pattern since it is simple and fast.
I used template based observer pattern. but I couldn't figure out how to make it two-way (i.e. both system and Bluetooth classes should be both subjects and observers at the same time to be able to observe each other).
the code that I imagined for it:
int main
{
System mySystem();
Bluetooth myBluetooth();
mySystem.attach(myBluetooth);
myBluetooth.attach(mySystem);
.
.
.
return 0;
}
1 Answer 1
The normal observer pattern can easily be used in a bidirectional way:
- One approach is that the two objects are reciprocal subjects and observers, i.e. both implement the two interfaces and register as observer of the other.
- Another approach is to use a variant of the observer, where the subject sends itself as parameter to the notification to the observer. The observer can the establish a bidirectional communication following an initial notification.
The questions is however what you want to achieve. Because the purpose of the observer is not to establish a communication channel, but notify that the state of an object did change. Other alternatives are:
- An event stream to which both object subscribe, consuling and publishing events.
- A mediator pattern, where a third object serves as intermediaty between many objects to coordinate their interaction.
Explore related questions
See similar questions with these tags.
main
is actually the system. I haven't done any programming to manage bluetooth connections, though, so my comments might be completely irrelevant.