设计模式——单例模式 - Go语言中文社区

设计模式——单例模式


常规写法

public class SingletonSample6
{
    //为了一个单例模式写很多的代码不合适,有一个懒人模式
    private static readonly Lazy<SingletonSample6> _instance = new Lazy<SingletonSample6>(() => new SingletonSample6());
    private int _counter = 0;

    //private外边不能被创建
    private SingletonSample6() { }

    //不能new 不能设值,开个只读的属性
    public static SingletonSample6 Instance
    {
        get
        {
            return _instance.Value;
        }
    }

    public int IncreaseCount()
    {
        return ++_counter;
    }
}

主窗体调用:

int count1 = SingletonSample6.Instance.IncreaseCount();
int count2 = SingletonSample6.Instance.IncreaseCount();

Console.WriteLine($"count1={count1},count2={count2}");
Console.ReadKey();

***out
count1=1,count2=2
***

接口写法

//写成一个基类,这样就不会每个单例都要写一堆代码
public class SingletonSampleBase<TSingleton> where TSingleton : class
{
    private static readonly Lazy<TSingleton> _instance = new Lazy<TSingleton>(() => (TSingleton)Activator.CreateInstance(typeof(TSingleton), true));

    protected SingletonSampleBase() { }

    public static TSingleton Instance
    {
        get
        {
            return _instance.Value;
        }
    }
}

使用:

 public class SingletonSample7 : SingletonSampleBase<SingletonSample7>
 {
     private int _counter = 0;

     private SingletonSample7() { }

     public int IncreaseCount()
     {
         return ++_counter;
     }
 }

调用:

int count1 = SingletonSample7.Instance.IncreaseCount();
int count2 = SingletonSample7.Instance.IncreaseCount();

Console.WriteLine($"count1={count1},count2={count2}");
Console.ReadKey();
***out
count1=1,count2=2
***

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_22824431/article/details/115469614
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2023-01-03 20:18:49
  • 阅读 ( 276 )
  • 分类:设计模式

0 条评论

请先 登录 后评论

官方社群

GO教程

推荐文章

猜你喜欢