Siwar
Siwar

Reputation: 217

more than one instance of singleton c#

Is there a realisation of a Singleton-like pattern which allows to create more than one instance?

My class definition is:

public class Logger
{
    private Logger(string logPath)
    {
        this.logPath = logPath;
    }


    /// <summary>
    /// Creates singleton 
    /// </summary>
    /// <param name="logPath"></param>
    /// <returns></returns>
    public static Logger GetInstance(string logPath)
    {
        lock (instanceLock)
        {
            if (logger == null)
            {
                logger = new Logger(logPath);
            }
        }
        return logger;
    }

    public static Logger Instance()
    {
        return logger;
    }

    /// <summary>
    /// Destructor
    /// </summary>
    ~Logger()
    {
        try
        {
            this.Close();
        }
        catch (Exception)
        {
        }
    }
}

Upvotes: 0

Views: 1499

Answers (3)

Volkan Talayhan
Volkan Talayhan

Reputation: 36

Here is a pattern i use for multiple singletons.

public sealed class CCTalk
{

    public string Port { get; set; }
    private CCTalk(string port)
    {
        this.Port = port;
    }
    private static Dictionary<string, CCTalk> _instances = new Dictionary<string, CCTalk>();

    public static CCTalk GetPortInstance(string port)
    {
        if (string.IsNullOrWhiteSpace(port)) return null;

        if (!_instances.ContainsKey(port))
        {
            _instances.Add(port, new CCTalk(port));
        }
        return _instances[port];
    }
}

Upvotes: 0

Timothy Shields
Timothy Shields

Reputation: 79441

This is the pattern I use:

public class Logger
{
    private Logger(...) { ... }

    static Logger { /* initialize Errors, Warnings */ }

    public static Logger Errors { get; private set; }
    public static Logger Warnings { get; private set; }

    public void Write(string message) { ... }
}

If you want to have a static Logger Lookup(string name) method, you can do that too.

Now in other code you can write Logger.Errors.Write("Some error"); or Logger.Warnings.Write("Some warning");.

Bonus: you can use Environment.StackTrace inside of your Write method to additionally log what method you called Write from.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564323

Is there a realisation of a Singleton-like pattern which allows to create more than one instance.

If you want multiple instances, just allow the class to be constructed directly, and don't make it a singleton. In your case, just make the constructor public, and remove the singleton/instance logic.

That being said, there is the Multiton pattern, which allows keyed access to multiple instances via a single interface.

Upvotes: 6

Related Questions