[Qt-interest] Non-Virtual Interface Idiom
Oliver.Knoll at comit.ch
Oliver.Knoll at comit.ch
Wed Dec 22 10:20:20 CET 2010
On 2010-12-21 Piotr Piotr Dobrogost wrote:
> On 2010-12-20 08:25, Andreas Pakulat wrote:
>
>> doDataPhase1&doDataPhase2. And of course it also means you cannot
>> override certain aspects of the actual data() implementation and hence
>> the concept limits the usability of classes designed this way.
>
> If you can't override certain aspects of base class' behavior that's
> because someone designed it this way and this is a Good Thing. Each
> class should be created to handle some task and handling any task means
> obeying some rules.
Exactly. And this is what the Template Method pattern is all about: it lais out a "plan" (or "pattern") and controls the *order* of the tiny little tasks, but the implementation of the tasks itself is up to the concrete implementation. And yes, that /is/ a Good Thing that any given subclass cannot easily break that "pattern" (off course every wrong implementation in any subclass can "ruin" the best laid out plan, but we are not talking about "ordinary bugs" here ;)
A typical example are "protocols", where the template method defines the *order* of the handshake, the request, the logging etc.:
class Communicator {
public:
...
void connect(const Parameter *param) {
allocateResources();
Authentication auth = authenticate();
request(param, auth);
awaitConfirmation();
...
}
private:
virtual void allocateResources();
virtual Authentication authenticate() = 0;
virtual void request(const Parameter *param, Authentication *auth);
virtual void awaitConfirmation();
...
};
So the concrete implementations can focus on the actual tasks (resource allocation, authentication), but the order in which they are executed is fixed. And yes, that /is/ a big advantage, it makes the protocol stable, and if you want to change its order (e.g. authentication before resource allocation) then is is to be done in just /one/ place, instead of all concrete implementations! Talk about "stable design" ;)
Another pattern would be not to use inheritance at all, but composition instead ("a Communicator *has* a Authentification component etc." - and yes, "subclassing is evil and dangerous" - I totally agree here with Herb!) which in this example would be even better....
Cheer, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22
More information about the Qt-interest-old
mailing list