开发者

Promoting code reuse for this situation

This is a bit tricky to explain but I will try my best to explain it.

I'm making a Gui API for games and it has Themes.

First I'll explain how Widgets work.

A Button for example, inherits from Widget. Themes work similarly.

ButtonTheme inherits from WidgetTheme.

Inside each widget class, there is an instance of its corrosponding Theme.

Widget class has:

    private:
   static WidgetTheme widgetTheme;
    public:
   static WidgetTheme& getWidgetTheme();

button class has:

  private:
    static ButtonTheme buttonTheme;
    public:
   static ButtonTheme& getButtonTheme();

the Widget constructor, builds itself from its theme ex:

Widget()
{
   setFont(getWidgetTheme().getFont());
}

the Button, inheriting from WidgetTheme, has to do the same ones be开发者_如何转开发cause the internal widget will not know to construct from ButtonTheme, so my button ends up having to do:

Button()
{
   setFont(getButtonTheme().getFont());
   setButtonPadding(getButtonTheme().getButtonPadding());
}

This is where my problem is. It really feels wrong that I have to reprovide all the WidgetTheme ones and redirect them to ButtonTheme's parameters for Widget. If I do not do this, a SuperButton would inherit the styles of Button which would also inherit the styles of Widget, but what I want is for SuperButton to use its version of ButtonTheme and WidgetTheme because SuperButtonTheme would inherit from ButtonTheme and WidgetTheme.

Is there a way I could redesign this so that the constructor only has to set parts of the theme that it brings, and not have to set those of its parents?

Thanks


A virtual getTheme() (as drewish suggests) but using covariant return types ought to solve your problem without requiring casts.


The Widget constructor can accept a WidgetTheme and use that.

Widget(const WidgetTheme& theme)
{
   setFont(theme.getFont());
}

Button() : Widget(getButtonTheme())
{
   setButtonPadding(getButtonTheme().getButtonPadding());
}


I'm not quite clear on where getButtonTheme() and getWidgetTheme() live in your object hierarchy but it seems like it should be up to the class to know what its theme is so why not have a getTheme() method on your class? Maybe I'm too used to scripting languages and not appreciating some issues with strict typing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜