简体   繁体   中英

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)
        {
        }
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM