C#设计模式之Singleton

添加人:iyond六级(3302分)   添加时间:2007-05-18    阅读次数:1571  收藏此教程
名称:Singleton
结构:
 
意图:
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
 
适用性 :
  1. 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
  2. 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。  
示例代码
// Singleton
namespace Singleton_DesignPattern
{
    using System;

    class Singleton
    {
        private static Singleton _instance;
        
        public static Singleton Instance()
        {
            if (_instance == null)
                _instance = new Singleton();
            return _instance;
        }
        protected Singleton(){}

        // Just to prove only a single instance exists
        private int x = 0;
        public void SetX(int newVal) {x = newVal;}
        public int GetX(){return x;}
    }

    /// <summary>
    /// Summary description for Client.
    /// </summary>
    public class Client
    {
        public static int Main(string[] args)
        {
            int val;
            // can't call new, because constructor is protected
            Singleton FirstSingleton = Singleton.Instance();
            Singleton SecondSingleton = Singleton.Instance();

            // Now we have two variables, but both should refer to the same object
            // Let's prove this, by setting a value using one variable, and
            // (hopefully!) retrieving the same value using the second variable
            FirstSingleton.SetX(4);
            Console.WriteLine("Using first variable for singleton, set x to 4");

            val = SecondSingleton.GetX();
            Console.WriteLine("Using second variable for singleton, value retrieved = {0}", val);
            return 0;
        }
    }
}
1页 第1上一页1下一页
相关的教程: CSharp 设计模式 Singleton
收藏此教程

当前平均分: 0.0(0 次打分)

-5-4-3-2-1012345
评论主题
您的大名
您的评论
验证码 点击换一个验证码
知识库搜索: