zoukankan      html  css  js  c++  java
  • Singleton模式

    Singleton模式的实现基于两个要点:

      1)不直接用类的构造函数,而另外提供一个Public的静态方法来构造类的实例。通常这个方法取名为Instance。Public保证了它的全局可见性,静态方法保证了不会创建出多余的实例。

      2)将类的构造函数设为Private,即将构造函数"隐藏"起来,任何企图使用构造函数创建实例的方法都将报错。这样就阻止了开发人员绕过上面的Instance方法直接创建类的实例。

      通过以上两点就可以完全控制类的创建:无论有多少地方需要用到这个类,它们访问的都是类的唯一生成的那个实例。以下C#代码展现了两种实现Singleton模式的方式,开发人员可以根据喜好任选其一。

      实现方式一:Singleton.cs

      using System;

      class SingletonDemo

      { private static SingletonDemo theSingleton = null;

      private SingletonDemo() {}

      public static SingletonDemo Instance()

      { if (null == theSingleton)

      {

      theSingleton = new SingletonDemo();

      }

      return theSingleton;

      }

      static void Main(string[] args)

      { SingletonDemo s1 = SingletonDemo.Instance();

      SingletonDemo s2 = SingletonDemo.Instance();

      if (s1.Equals(s2))

      { Console.WriteLine("see, only one instance!");

      }

      }

      }

      与之等价的另外一种实现方式是:Singleton.cs:

      using System;

      class SingletonDemo

      { private static SingletonDemo theSingleton = new SingletonDemo();

      private SingletonDemo() {}

      public static SingletonDemo Instance()

      { return theSingleton;

      }

      static void Main(string[] args)

      { SingletonDemo s1 = SingletonDemo.Instance();

      SingletonDemo s2 = SingletonDemo.Instance();

      if (s1.Equals(s2))

      { Console.WriteLine("see, only one instance!");

      }

      }

      }

  • 相关阅读:
    getElementById返回的是什么?串讲HTML DOM
    DIV+CSS布局问题:一个宽度不确定的DIV里面放三个水平对齐的DIV,左右两个DIV宽度固定为150px,中间那个DIV充满剩余的宽度
    原生JavaScript拖动div兼容多种浏览器
    java一切乱码的解释 以及源头【转】
    java编码问题深入总结
    三菱Q系列PLC基本指令讲解
    三菱Q系列PLC的io分配
    linux函数的阻塞与非阻塞IO及错误处理
    linux系统编程之文件IO
    linux命令(shell)
  • 原文地址:https://www.cnblogs.com/sohobloo/p/2312330.html
Copyright © 2011-2022 走看看