1. 静态单例
using System;
using System.Collections.Generic;
namespace InstanceTest
{
public class DogManager {
public static readonly DogManager Instance = new DogManager();
private DogManager() { }
public void Eat() {
Console.WriteLine("吃");
}
}
class Program
{
static void Main(string[] args)
{
DogManager.Instance.Eat();
}
}
}
2.延时单例
using System;
using System.Collections.Generic;
namespace InstanceTest
{
public class DogManager {
private static DogManager _instance = null;
private DogManager() { }
public static DogManager Insance() {
if (_instance == null) {
_instance = new DogManager();
}
return _instance;
}
public void Eat() {
Console.WriteLine("吃");
}
}
class Program
{
static void Main(string[] args)
{
DogManager.Insance().Eat();
}
}
}
注意把构造函数写成private,让他不能通过new获得。
网友评论