dimanche 6 décembre 2015

How to do different things according to type but not using overriding?

For example, I have some Shape, and each shape return different types of buttons:

#include <stdio.h>
struct Button{
    Button(){
        printf("Button\n");
    }
};

struct CircleButton : public Button{
    CircleButton(){
        printf("CircleButton\n");
    }
};

struct SquareButton : public Button{
    SquareButton(){
        printf("SquareButton\n");
    }
};

struct Shape{
    virtual Button* getNewButton()=0;
};

struct Circle : public Shape{
    Button* getNewButton(){
        return new CircleButton();
    }
};

struct Square : public Shape{
    Button* getNewButton(){
        return new CircleButton();
    }
};

by using override I can write some generic code:

int main(){
    Shape* s=new Circle();
    Button* b=s->getNewButton();
    return 0;
}

but now the shape is data transfer object, which should not have any methods:

struct Shape{
};

struct Circle : public Shape{
};

struct Square : public Shape{
};

and I want to keep my generic code, I tried:

struct Helper{
    static Button* getNewButton(Shape* s){
        return new Button();
    }

    static Button* getNewButton(Circle* s){
        return new CircleButton();
    }

    static Button* getNewButton(Square* s){
        return new SquareButton();
    }
};

int main(){
    Shape* s=new Circle();
    Button* b=Helper::getNewButton(s);
    return 0;
}

but this time I cannot get a new CircleButton, how to modify the code, or what design pattern can apply, so that I can get different type of button according to different shape, but not overriding shape?

Aucun commentaire:

Enregistrer un commentaire