Using .NET 4's Lazy 实现单实例

时间:2023-03-08 22:33:11

Using .NET 4's Lazy<T> type
 
Explanation of the following code:

  1. If you're using .NET 4 (or higher) then you can use the System.Lazy<T> type to make the laziness really simple.
  2. All
    you need to do is pass a delegate to the constructor that calls the
    Singleton constructor, which is done most easily with a lambda
    expression.
  3. It also allows you to check whether or not the instance has been created with the IsValueCreated property.

public sealed class Singleton

{

private Singleton()

{

}

private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

public static Singleton Instance

{

get

{

return lazy.Value;

}

}

}

Example:
 
The final example is here:

namespace Singleton

{

class Program

{

static void Main(string[] args)

{

Calculate.Instance.ValueOne = 10.5;

Calculate.Instance.ValueTwo = 5.5;

Console.WriteLine("Addition : " + Calculate.Instance.Addition());

Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());

Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());

Console.WriteLine("Division : " + Calculate.Instance.Division());

Console.WriteLine("\n----------------------\n");

Calculate.Instance.ValueTwo = 10.5;

Console.WriteLine("Addition : " + Calculate.Instance.Addition());

Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());

Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());

Console.WriteLine("Division : " + Calculate.Instance.Division());

Console.ReadLine();

}

}

public sealed class Calculate

{

private Calculate()

{

}

private static Calculate instance = null;

public static Calculate Instance

{

get

{

if (instance == null)

{

instance = new Calculate();

}

return instance;

}

}

public double ValueOne { get; set; }

public double ValueTwo { get; set; }

public double Addition()

{

return ValueOne + ValueTwo;

}

public double Subtraction()

{

return ValueOne - ValueTwo;

}

public double Multiplication()

{

return ValueOne * ValueTwo;

}

public double Division()

{

return ValueOne / ValueTwo;

}

}

}