mardi 1 août 2017

Is this kind of design pattern?

Suppose we have oversimplified code like this:

class A{
public:
    template<typename T1, typename T2>
    void work(T1 a, T2 b){
        do_something1(a, b);
        do_something2(a, b);
        do_something3(a, b);
    }

private:
    template<typename T1, typename T2>
    void do_something1(T1 a, T2 b);

    template<typename T1, typename T2>
    void do_something2(T1 a, T2 b);

    template<typename T1, typename T2>
    void do_something3(T1 a, T2 b);
};

All functions do_somethingXX have same or similar template parameters and probably have some boilerplate code inside.

However, if you refactor like this:

class A{
public:
    template<typename T1, typename T2>
    void work(T1 a, T2 b){
        A_Processor<T1, T2> processor(a, b);

        processor();
    }
};

template<typename T1, typename T2>
class A_Processor{
public:
    A_Processor(T1 &a, T2 &b) : a(a), b(b){}

    operator()(){
        do_something1();
        do_something2();
        do_something3();
    }

private:
    void do_something1();
    void do_something2();
    void do_something3();

private:
    T1 &a;
    T2 &b;
};

Code is much clear and boilerplate disappear. Also compiler optimize A_Processor away, so A_Processor is zero cost abstraction.

One can give same example without using templates.

Is this kind of design pattern?

Second question if A is class A what "thing" A_Processor represents?

Aucun commentaire:

Enregistrer un commentaire