设计模式实践-单例

场景

全局配置文件

实现代码

配置文件实现:

namespace DesignPatterns.Singleton
{
    /// <summary>
    ///     配置文件类型
    /// </summary>
    public class ServerConfig
    {
        /// <summary>
        ///     Gets or sets IP
        /// </summary>
        public string Ip { get; set; }

        /// <summary>
        ///     Gets or sets Port
        /// </summary>
        public uint Port { get; set; }
    }
}

单例实现:

namespace DesignPatterns.Singleton
{
    /// <summary>
    /// ConfigSingleton Class
    /// </summary>
    public class ConfigSingleton
    {
        /// <summary>
        /// ConfigSingleton Instance  
        /// </summary>
        private static readonly ConfigSingleton Instance;

        /// <summary>
        /// Initializes static members of the <see cref="ConfigSingleton" /> class. 
        /// </summary>
        static ConfigSingleton()
        {
            Instance = new ConfigSingleton();
        }

        /// <summary>
        /// Prevents a default instance of the <see cref="ConfigSingleton" /> class from being created.
        /// </summary>
        private ConfigSingleton()
        {
            ServerConfig = new ServerConfig
            {
                Ip = "127.0.0.1",
                Port = 8000
            };
        }

        /// <summary>
        /// Gets ServerConfig
        /// </summary>
        public ServerConfig ServerConfig { get; }

        /// <summary>
        /// Get ConfigSingleton Instance
        /// </summary>
        /// <returns>ConfigSingleton Instance</returns>
        public static ConfigSingleton GetInstance()
        {
            return Instance;
        }
    }
}

相关调用

var config = ConfigSingleton.GetInstance().ServerConfig;
Console.WriteLine(config.Ip);
Console.WriteLine(config.Port);           

Out:

127.0.0.1
8000       
posted @ 2016-07-06 22:39  4Thing  阅读(86)  评论(0编辑  收藏  举报