用C#改写Head First Design Patterns--SingleTon(原创)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SingleTon
{
    public sealed class SingleObject
    {
        //公有字段
        public string name;


        //类似java的实现
        private static object syncRoot = new Object();
       
        //私有字段
        private volatile static SingleObject uniqueObj;

        private SingleObject(string name)
        {
            this.name = name;
        }

        public static SingleObject getInstance(string n)
        {
            if (uniqueObj == null)
            {
                //lock (typeof(SingleObject))
                lock (syncRoot)
                {
                    uniqueObj = new SingleObject(n);
                }
            }

            return uniqueObj;
        }

       
        //private static readonly SingleObject instance = new SingleObject();
        //private SingleObject() { }
        //public static SingleObject Instance
        //   {
        //      get 
        //      {
        //         return instance; 
        //      }
        //   }

 

    }
}

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SingleTon
{
    class Program
    {
        static void Main(string[] args)
        {
            SingleObject s = SingleObject.getInstance("a");
            SingleObject s1 = SingleObject.getInstance("b");

            System.Console.WriteLine(s.name);
            System.Console.WriteLine(s1.name);

            System.Console.ReadLine();

        }
    }
}

 

你可能感兴趣的:(design pattern)