单例模式:
饿汉模式创建单例:
所谓的”饿汉模式“,就是在类加载时就完成了初始化,所以类加载的速度较慢,但是获取对象的速度快
缺点:因为类在加载时就完成了实例化,所以不确定该实例有没有被使用,这样的话内存就浪费啦
实现代码:
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
}
;
public static Singleton getInstance(){
return singleton;
}
}
测试类:
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(()->{
Singleton instance = Singleton.getInstance();
System.out.println(Thread.currentThread().getName()+":"+instance);
}).start();
}
}
懒汉模式创建单例:
所谓的”懒汉模式“,就是在类加载的时候不会初始化,而是在第一次被使用的时候初始化
懒汉模式创建单例有以下几种方式:
①普通懒汉模式
实现代码:
public class Singleton01 {
private static Singleton01 singleton01;
private Singleton01() {
}
;
public static Singleton01 getInstance() {
if (singleton01 == null) {
singleton01=new Singleton01();
}
return singleton01;
}
}
测试类”:
@Test
public void test(){
for (int i = 0; i < 20; i++) {
new Thread(()->{
Singleton01 instance = Singleton01.getInstance();
System.out.println(Thread.currentThread().getName()+":"+instance);
}).start();
}
}
②同步方法懒汉模式
实现代码:
public class Singleton02 {
private static Singleton02 singleton02;
private Singleton02() {
}
;
public static synchronized Singleton02 getInstance() {
if (singleton02 == null) {
singleton02 = new Singleton02();
}
return singleton02;
}
}
测试类:
@Test
public void test1(){
for (int i = 0; i < 20; i++) {
new Thread(()->{
Singleton02 instance = Singleton02.getInstance();
System.out.println(Thread.currentThread().getName()+":"+instance);
}).start();
}
}
③双重检查锁懒汉模式
实现代码:
public class Singleton03 {
private static volatile Singleton03 singleton03;
private Singleton03() {
}
;
public static Singleton03 getInstance() {
if (singleton03 == null) {
synchronized (Singleton03.class) {
if (singleton03 == null) {
singleton03 = new Singleton03();
}
}
}
return singleton03;
}
}
测试类:
@Test
public void test2(){
for (int i = 0; i < 20; i++) {
new Thread(()->{
Singleton03 instance = Singleton03.getInstance();
System.out.println(Thread.currentThread().getName()+":"+instance);
}).start();
}
}
④静态内部类懒汉模式
实现代码:
public class Singleton04 {
private Singleton04(){};
private static class SingleHolder{
private static Singleton04 singleton04=new Singleton04();
}
public static Singleton04 getInstance(){
return SingleHolder.singleton04;
}
}
测试类:
@Test
public void test3(){
for (int i = 0; i < 20; i++) {
new Thread(()->{
Singleton04 instance = Singleton04.getInstance();
System.out.println(Thread.currentThread().getName()+":"+instance);
}).start();
}
}
单例模式的优点和缺点:
优点:单例模式只有一个实例,所以节省了内存资源,而对于一些频繁需要销毁的对象可以选择使用单例模式,这样会大大提高系统性能;单例模式还可以在系统设置全局的访问点,优化和共享数据;
缺点:单例模式一般没有接口,扩展和后期维护只能修改代码,不符合设计模式的开闭原则。