I am creating a custom control and it is a button. It may has a type and a specified image according to its type. Its type may be:
public enum ButtonType
{
PAUSE,
PLAY
}
Now I can change its appearance and Image with a method:
public ButtonType buttonType;
public void ChangeButtonType(ButtonType type)
{
// change button image
if (type == ButtonType.PAUSE)
button1.Image = CustomButtonLibrary.Properties.Resources.PauseButton;
else if (type == ButtonType.PLAY)
button1.Image = CustomButtonLibrary.Properties.Resources.PlayButton;
buttonType = type;
}
OK, this method doesn’t seems so good, for example maybe later I wish to have another type STOP for example for this button, I want just add its image to resources and add it to ButtonType enum, without changing this method.
How can I implement this method to be compatible with future changes?
One thing you can do is turn
ButtonTypeinto a base class (or an interface, if you prefer):Then each of your types becomes a subclass:
Your image changing method then becomes:
This way when you want to add another type, you add another ButtonType subclass and pass it to your
ChangeButtonTypemethod.Since this method is on your custom button class, I would probably take this a bit further and encapsulate style/appearance in a class:
And then on the button itself:
You could set up button behaviours (i.e. actions they perform when they’re clicked) in a similar way with a ButtonAction base class and assigning specific actions like Stop and Play when you want to change the button’s purpose and style.