Single Design Mode

Source: Internet
Author: User
单体模式简介:

     单体模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

实现思路

     如果要求该类只能实例化一次,通常的做法是:

1、  在类中声明一个标志变量,用来查看该类是否被实例化。

2、  将该类的构造函数私有化,使其只能在类中访问。

3、  写一个静态方法,用于外面调用实例化类。如果类已经存在则就不再实例化。

实现

   这里用一个person类举例。

创建一个person类

public class Person    {      private static Person person =null;      private DateTime _birthday=newDateTime(1990,12,12);       public DateTime Birthday      {          get { return _birthday; }          set { _birthday = value; }      }      private Person()      {      }      public static PersonGetInstance()      {          if (person == null)          {              person = new Person();          }          return person;      }}


在外部调用方法

  static void Main(string[] args)        {            Person person = Person.GetInstance();            DateTime birthday = DateTime.Now;            person.Birthday =birthday;            Console.WriteLine("{0:D}",person.Birthday);             //再次的到实例            Person per = Person.GetInstance();            Console.WriteLine("{0:D}",per.Birthday);            Console.Read();         }


运行输出的都是当前日期,可见是同一个实例。

总结

     受以前辈教导:参加工作,要对自己写的代码做整理。最好要有自己的代码库,不要遇到做过的问题再重新做一遍。

单体设计模式

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.