class Singleton{
//1.构造器私有化,外部不能new
private Singleton(){
}
//2.本类内部创建对象实例
private final static Singleton instance = new Singleton();
//3.提供一个公有的静态方法,返回实例对象
public static Singleton getInstance(){
return instance;
}
}
class Singleton {
//1.构造器私有化,外部不能new
private Singleton() {
}
//2.本类内部创建对象实例
private static Singleton instance;
static { //在静态代码块中,创建单例对象
instance = new Singleton();
}
//3.提供一个公有的静态方法,返回实例对象
public static Singleton getInstance() {
return instance;
}
}
class Singleton {
private static Singleton instance;
private Singleton() {
}
//提供一个静态的公有方法,当使用到方法时,才去创建instance
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
class Singleton {
private static Singleton instance;
private Singleton() {
}
//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
class Singleton {
private static volatile Singleton instance; //volatile保证线程间的可见性
private Singleton() {
}
//提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题
//同时保证了效率,推荐使用
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
class Singleton {
private Singleton() {
}
//写一个静态内部类,该类中有一个静态属性Singleton
//在调用getInstance()方法时,静态内部类才会被装载,保证了懒加载;同时类加载是线程安全的
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
//提供一个静态的公有方法,直接返回SingletonInstance.INSTANCE
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
enum Singleton{
INSTANCE; //属性
public void doSomething(){
System.out.println("do something");
}
}
Linux 发行版的爱好者们又有全新的 Linux 可以体验了,日前一款名为 TeLOS 的 Li...
Afrikaans:af Albanian:sq Basque:eu Belarusian:be Bulgarian:bg Catalan:ca Ch...
一. RabbitMQ 简介 MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用...
Eval 计算一个表达式的值并返回结果。 语法:[result = ]eval_r(expression_r) e...
本文分享自华为云社区《 架构可视化支撑系统演进探索 》原文作者无名小溪。 随着...
今天给大家分享四个在实际开发中,比较实用的SQL Server脚本函数,希望对大家能...
如果你想对使用手机,平板电脑和辅助技术的用户隐藏某些内容,而只对键盘用户显...
一、导读 本文主要介绍Redhat7.6系统安装oracle 12201版本RAC的一些坑以及避坑方...
ajax传送json格式数据,关键是指定contentType,data要是json格式 如果是restful...
最近在和团队规划OKR目标的时候,我们讨论了很多问题,我先抛砖引玉,列举了一些...