mercredi 1 mars 2017

How do you call an interface standing between a class and its base class?

Note: I tagged design patterns just in (the unlikely) case it is actually one. If it's not I'll remove the tag.

consider this example:

template <class _base>
struct SplitPrint: public _base
{
    virtual void printPositive(int positive) = 0;
    virtual void printNegative(int negative) = 0;
    void print( int number) override
    { 
        _base::print(number);
        if (number >= 0)
            printPositive(number);
        else
            printNegative(number);
    }
};

struct Interface
{
    virtual void print( int number) = 0;
};

//implements the interface
struct NormalImplementer : public Interface
{
    void print( int number) override { std::cout << number << "\n"; }
};

//Still implements the interface
struct DifferentImplementer : public SplitPrint<NormalImplementer>
{
    void printPositive (int number) override { if (number > 10) std::cout << "big" << "\n"; }
    void printNegative (int number) override { if (number < -10) std::cout << "small" << "\n"; }
};

//Still implements the interface
struct TellSign : public SplitPrint<DifferentImplementer>
{
    void printPositive (int number) override { std::cout << "also, positive" << "\n"; }
    void printNegative (int number) override { std::cout << "also, negative" << "\n"; }
};


int main()
{
  NormalImplementer printer1;
  DifferentImplementer printer2;
  TellSign printer3;

  printer1.print(5); //5
  printer1.print(-42); //-42

  printer2.print(5); //5
  printer2.print(-42); //-42 small

  printer3.print(5); //5 also, positive
  printer3.print(-42); //-42 small also, negative
}

Here I split the pure virtual method "print" in two other methods, DifferentImplementer doesn't have to know how to print a number (silly example but hopefully you understand what I mean) as long as it knows how to print a positive number and how to print a negative one.

Do this OOP problem have a name? Is this example a good way to solve this problem in C++? is there a better/cleaner way to solve this problem in C++?

Aucun commentaire:

Enregistrer un commentaire