首页 > 代码库 > .NET设计模式之(单例模式)

.NET设计模式之(单例模式)

1.单例模式,一个类只能new一个对象

2.举例,资源管理器,文件管理器,地球等;

3.创建单例:

(1)创建一个Earth类

class Earth

{

       public Earth()

       {


        }

}

(2)将构造函数 私有化

class Earth

{

       private Earth()

       {


        }

}

(3)声明一个静态私有的字段,初始化一个实例

class Earth

{

       private static Earth instance=new Earth();

       private Earth()

       {


        }

}

(4)编写一个静态方法或属性,返回唯一的实例

class Earth

{

       private static Earth instance=new Earth();

       public static Earth GetEarth()

       {

                  return instance;

       }

       private Earth()

       {


        }

}