Your approach is just as correct if some created a subclass just to override a method. One of the main reasons of OOP is for a simple modular design of programs. When you think about it from philosophical stand point your button bar is a different kind of object to a container the difference may seem trivial in a small program but in a larger one it could make the difference of the program being comprehensible.
Is it OK to subclass solely to provide default state/configuration?
-
24-06-2022 - |
문제
Say you have a GUI framework that supports nesting GUI components inside one another. Let's call the base class for any GUI component that can contain other GUI components a Container.
Is it OK to subclass Container soley to provide default configuration, or should subclassing always provide addition/override/implemented behavior? For example, say I wanted to make a ButtonBar container that filled up 100% of the screen width, was 50 pixel in height, and laid out its components horizontally. To configure a Container like that, I could do either of the following two examples:
Container container = new Container();
container.PercentWidth = 100;
container.Height = 50;
container.Layout = Layout.Horizontal;
// use container
OR, (and this is my question), is it OK to do this:
public class ButtonBar : Container
{
public ButtonBar()
{
PercentWidth = 100;
Height = 50;
Layout = Layout.Horizontal;
}
}
ButtonBar buttonBar = new ButtonBar();
// use buttonBar
ButtonBar has no additional functionality over a container, and overrides no Container methods. It just serves to ease configuring a Container to be a ButtonBar.
Edit
I have concluded that it is probably best to use a factory that returns a Container, such as widgetFactory.CreateButtonBar(); This way, you end up using an abstract type (Container), and encapsulate the 'set-up' of the type in a factory, which is what factories do.
public class WidgetFactory
{
public Container CreateButtonBar()
{
Container container = new Container();
container.PercentWidth = 100;
container.Height = 50;
container.Layout = Layout.Horizontal;
return container;
}
}
해결책
다른 팁
Actually nothing speaks against the approach you're taking. The only problem is see here is that C# has no multi-inheritance so you can only subclass one "Container".
How about instead just holding the container as kinda template and access the properties from that one?
Exampe here
public enum ContainerLayout {
Horizontal,
Vertical
}
public class Container
{
public int PercentWidth { get; set; }
public int Height { get; set; }
public ContainerLayout Layout { get; set; }
}
public class ButtonBar
{
public Container containerTemplate = null;
public ButtonBar(Container strategy)
{
containerTemplate = strategy;
}
}
// Creation would be
ButtonBar btnBar = new ButtonBar(
new Container()
{
PercentWidth = 100,
Height = 700,
Layout = ContainerLayout.Horizontal
}
);