design mode (C #)

Source: Internet
Author: User
Tags datetime

Returns the design mode (C #) series Article index

Introduced

Guarantees that a class has only one instance and provides a global access point to access it.

Example

Ensure that a class has only one instance.

Singleton

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

namespace Pattern.Singleton
{
  /**//// <summary>
  /// 泛型实现单例模式
  /// </summary>
  /// <typeparam name="T">需要实现单例的类</typeparam>
  public class Singleton<T> where T : new()
  {
    /**//// <summary>
    /// 返回类的实例
    /// </summary>
    public static T Instance
    {
      get { return SingletonCreator.instance; }
    }

    class SingletonCreator
    {
      internal static readonly T instance = new T();
    }
  }
}

Test

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using system.web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Pattern.singleton;

public partial class Singleton:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e) br> {
//Use singleton mode to ensure that a class has only one instance
Response.Write (Singleton<test>. Instance.time);
Response.Write ("<br/>");
Response.Write (Singleton<test>. Instance.time);
Response.Write ("<br/>");     

//No single case mode
Test t = new test ();
Response.Write (T.time);
Response.Write ("<br/>");
Test t2 = new Test ();
Response.Write (T2. Time);
Response.Write ("<br/>");
}
}

public class Test
{
Private datetIME _time;     

Public Test ()
{
System.Threading.Thread.Sleep (3000);
  _time = DateTime.Now;
}

public string time
{
get {_time. ToString (); }
}

Run results

2007-2-10 22:35:11
2007-2-10 22:35:11
2007-2-10 22:35:14
2007-2-10 22:35:17

Reference

Http://www.dofactory.com/Patterns/PatternSingleton.aspx

Ok

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.