Bryan Watts
Bryan Watts

Reputation: 45445

Is this a legitimate use of a Singleton?

(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.

Upvotes: 0

Views: 258

Answers (3)

tvanfosson
tvanfosson

Reputation: 532435

If you only want the template created once for the control, you could use lazy initialization instead and achieve nearly the same effect.

private ITemplate defaultTemplate;
public override ITemplate CreateDefaultTemplate()
{
     if (defaultTemplate == null)
     {
         defaultTemplate = new FooTemplate();
     }
     return defaultTemplate;
}

You should only use a Singleton implementation if you are sure that you only want one instance of any particular object ever in your application.

Upvotes: 1

Robert Wagner
Robert Wagner

Reputation: 17793

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.

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351486

Do you really want to use the exact same instance for the template control? We may need some more info about what you are trying to accomplish. How many places does TemplatedControl get used in the same application?

Upvotes: 0

Related Questions