欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

设计模式系列 - 单例模式

程序员文章站 2022-10-04 20:11:02
单例模式就是指单例类在一定的生命周期内只能有一个对象实例,单例类的创建必须是本身,并能给使用者提供自身。 介绍 在现实世界中,每个生命体都可以被看做是一个单例对象,唯一且具体,具有不可复制性。同样的,在软件开发领域中,有时我们需要保证客户端在当前的客户机上只能运行一个实例这个时候,我们就应该考虑使用 ......

单例模式就是指单例类在一定的生命周期内只能有一个对象实例,单例类的创建必须是本身,并能给使用者提供自身。

介绍

在现实世界中,每个生命体都可以被看做是一个单例对象,唯一且具体,具有不可复制性。同样的,在软件开发领域中,有时我们需要保证客户端在当前的客户机上只能运行一个实例这个时候,我们就应该考虑使用单例模式来实现这种业务场景。

类图描述

代码实现

1、懒汉式,线程不安全

public class singleobject
{
    private static singleobject _instance;

    private singleobject()
    {
    }

    public static singleobject getinstance() => _instance ?? (_instance = new singleobject());

    public void showmessage()
    {
        console.writeline("hello world");
    }
}

2、懒汉式,线程安全

public class singleobject
{
    private static singleobject _instance;

    private static readonly object _locker = new object();

    private singleobject()
    {

    }

    public static singleobject getinstance()
    {
        if (_instance == null)
        {
            lock (_locker)
            {
                if (_instance == null)
                {
                    _instance = new singleobject();
                }
            }
        }

        return _instance;
    }

    public void showmessage()
    {
        console.writeline("hello world");
    }
}

3、静态内部类延迟加载

public class singleobject
{
    public static singleobject getinstance() => nested.instance;

    private sealed class nested
    {
        static nested()
        {
        }
        internal  static readonly  singleobject instance = new singleobject();
    }
    public void showmessage()
    {
        console.writeline("hello world");
    }
}

4、上层调用

class program
{
    static void main(string[] args)
    {

        singleobject.getinstance().showmessage();
        console.readkey();
    }
}

总结

对于单例模式,较为好理解,如果需要保持对象的唯一性,则可以考虑使用这种模式进行解决。