设计模式----单例模式UML图和代码实现(C#&JAVA)

1、什么是单例模式?

定义:单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点
java

2、单例模式UML图

3、单例模式C#版

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DP
{
    class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {
        }
        public static Singleton getInstance()
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}



4、单例模式JAVA版

public class Singleton {
	private static Singleton instance;

	private Singleton() {
	}

	public static Singleton getInstance() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}


5、扩展

上面的实现其实都是属于懒汉式的实现,即引用时才进行初始化;下面介绍一下饿汉式的实现,即调用时即进行初始化
c#

JAVA版实现spa

public class ESingleton {
	private static final ESingleton instance = new ESingleton();

	private ESingleton() {
	}

	public static ESingleton getInstance() {
		return instance;
	}
}


C#版实现code

class ESingleton
    {
        private static readonly ESingleton instance = new ESingleton();
        private ESingleton()
        {
        }
        public static ESingleton getInstance()
        {
          return instance;
        }
    }
相关文章
相关标签/搜索