My question concerns general design of programs. When object a wants to send information to object b there are three possibilities:
Control is outside of objects a and b and public methods of a and b are called:
b.TakeInformation(a.getInformation());
- Control is inside of b:
In this case b
does what it wants and sometimes asks a
for information:
class A {
public Information getInformatino() {
// code omitted
}
// code omitted
}
class B {
// code omitted
void foo() {
while (bar()) {
information = a.getInformation();
DoSomeWork(information);
}
}
}
- Control is inside of
a
:
In this case a
does what it wants and sometimes it gives b infromation it is producing:
class A {
// code omitted
void foo() {
while (bar()) {
information = produceInformation()
b.TakeInformation(information)
}
}
}
class B {
// code omitted
public void TakeInformation(information) {
// code omitted
}
}
What interests me the most is the fourth possibility with both a
and b
being callers and with none of them being callees.
The simplest answer what to do in such situation is: Rewrite one of the classes so that it is callee.
This does not satisfy me. For example let us suppose that A some strange kind of stream which doesn't allow me to read characters by calling a method ReadChar() a.k.a. getInformation() but instead it is a caller and every time a character is read from the input it calls b.giveInformation(character)
.
Suppose that I can't rewrite the class A. Then imagine that I program a class B which is a parser of some language. The parser B consists of a lot of functions and helping classes and uses ReadChar on many places in code.
The solution of the problem would require to rewrite class B so that it is called by giveInformation(character)
instead of calling ReadChar()
. That would be extremely painful and unintuitive.
The most elegant solution to this synthetic example would be creating the adapter which starts A
and stores all the characters and then starts B
and provides it the nececarry interface for reading characters.
Unfortunately this is not applicable in other scenarios when classes A
anb B
are communicating in both directions.
How can one generally solve such tasks?
Are there some programming languages with nonstandard paradigms where this task wouldn't be problem?
A several possible solutions or approaches comes to my mind. They consist of threads, pipes, assembly language or abuse of lazy evaluation, but none of them seem good enough or I don't know how to use them. I will summarize my ideas in an answer.
Thanks for any help.
Aucun commentaire:
Enregistrer un commentaire