Java如何定义一个最简单的单例模式呢?
下文笔者讲述使用java代码定义单例模式的代码分享,如下所示
定义一个单例模式
实现思路:
1.定义一个static类
2.使用synchronized定义获取单例类的方法
例:定义一个单例模式
/**
*单例设计模式之懒汉式
*/
public class SingletonInstance {
private static SingletonInstance instance = null;
private SingletonInstance() {
}
public static synchronized SingletonInstance getInstance() {
if (instance == null) {
instance = new SingletonInstance();
}
return instance;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


