(Disclaimer: This question is not specific to ASP.NET)
I have a control which may be templated, similar to the login controls:
public abstract class TemplatedControl : CompositeControl { public ITemplate Template { get; set; } protected override void CreateChildControls() { var template = this.Template ?? CreateDefaultTemplate(); // ... } protected virtual ITemplate CreateDefaultTemplate() { return null; } }
A templated control would look like:
public class FooControl : TemplatedControl { public override ITemplate CreateDefaultTemplate() { return new FooTemplate(); } }
My question is: would a Singleton be appropriate here instead?
public override ITemplate CreateDefaultTemplate() { return FooTemplate.Instance; }
Singletons are associated with global variables; in this case, there is no state.
Singletons are also associated with hard-coded dependencies. In this case, knowledge of the specific type is warranted.
In this case I would say not. In the pattern you are proposing, there would only ever be one FooTemplate, which would be shared across multiple controls, pages and threads. You would have to be very careful that the template did not contain any request or user specific information, and also synchronize any method calls. It is much easier, and just a bit less performant to instantiate it each time.
The only reason I see doing it that was is that it takes a long time to instantiate the control. In that case, I would go with a factory pattern, where any initialization is done once, but all the data copied into a new instance every time.