I am dynamically adding and replacing controls in a winform panel at runtime
Even though all works I have been told to implement interfaces rather than inheriting from a baseUserControl.
I am all for it but I dont see how I can I achieve the same result using interfaces
How would I code my Factory?
How can this be improved and use interfaces instead ?
//Simplified noddy example
//Client code
var controlA = ControlFactory
.Create("UserControlA") as UserControlA;
panel1.Controls.Add(ControlA);
//Factory
public class ControlFactory
{
public static BaseUserControl Create(string name)
{
switch (name)
{
case "UserControlA":
var userControlA = new UserControlA();
return userControlA;
case "UserControlB":
var userControlB = new UserControlB();
return userControlB;
}
return null;
}
}
//BaseUserControl
public partial class BaseUserControl : UserControl
{
public BaseUserControl()
{
InitializeComponent();
}
public virtual void DoSomething()
{
}
}
public partial class UserControlA : BaseUserControl
{
public UserControlA()
{
InitializeComponent();
}
public override void DoSomething()
{
//Do something here
}
}
public partial class UserControlB : BaseUserControl
{
public UserControlB()
{
InitializeComponent();
}
public override void DoSomething()
{
//Do something here
}
}
Here’s how you can do it:
You can retain
BaseUserControlif you have any functionality that is common toUserControlAandUserControlB; otherwise, eliminate it and make the latter two derive directly fromUserControl.You should define all members you might need to access from your derived classes within your
IControlinterface. This includes any members you will inherit fromUserControl. However, you will not need to re-implement these within your concrete classes.If you need to add these controls to a Windows Forms application – typically as the argument to a
Control.ControlCollection.Addmethod call – you will need to get aControlinstance corresponding to your control. Under the current implementation, this may be achieved simply through casting; however, this needs to be insulated from the consumers of your interface, in case you decide to change the underlying implementation in the future. Thus, I would use:In your client code: