I'm answering in a general manner here.
I don't think a singleton pattern would fit well with form management. Generally, you want to pass some context parameter to the form, and you might want to open multiple instances of the same form. So a singleton doesn't fit well IMO.
I think form management should be simple.
For instance, if you want to display a modal form from another form, I would write something really straightforward:
private void button1_Click(object sender, EventArgs e)
{
using (ModalForm1 frm = new ModalForm1(myParam))
{
frm.ShowDialog();
if (frm.MyResultProperty == ...)
{
// Do some job here
}
}
}
Of course you could write some interface/generics syntax to avoid a little code duplication in case you want to display a lot of modal forms:
public interface IFormResult<T>
{
T Result { get; set; }
}
public class ModalForm1 : Form, IFormResult<string>
{
public ModalForm1()
{
InitializeComponent();
this.Result = "My result";
}
public string Result { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
string res = ShowModalForm<ModalForm1, string>();
}
private static T2 ShowModalForm<T1, T2>()
where T1 : Form, IFormResult<T2>, new()
{
using (T1 form = new T1())
{
form.ShowDialog();
return form.Result;
}
}
But honestly, I feel like it's a bit overingeneered.
Second point: if your form doesn't exactly follows this specific behavior (ShowDialog()
then a Result
property is set), then you must write another Interface...etc.
If this type of syntax (generics, interfaces...etc.) doesn't reduce the number of lines of code written OR the complexity OR the maintainability (and obviously we can't say it's really the case here), then it's pretty useless IMO.
Edit:
Form management really depends on your use case.
- If you have say 20 forms that can be displayed at the same time, then you should think of a
FormManager
concept (or better: think about how to improve the user experience by reducing the number for possible opened forms)
- If you have something relatively simple (2-3 modeless forms at the same time + 3-4 possible modal forms), I wouldn't write complex code to manage those forms.
Generally, the form that is used to start the application (i.e. the form that stops the program when closed, which is the form that is a parameter of Application.Run()
) is responsible of other forms. You have one main form, and multiples child forms. If your case is really different, then there is probably something smarter to write, but it'll depend on your case. I don't think one can provide a general good answer to the general problematic of form management.
Honestly, if you want something really maintainable, try to reduce (as much as possible) the number of forms that can be shown at the same time. Multiple displayed modeless forms at the same time doesn't offer a good user experience in most cases, and form lifetime management can be problematic if forms are dependent on each other.