设计模式之原型模式(TODO)
频繁用到的重复对象 跟远程频繁访问数据库资源的情况下考虑原型模式
单例模式
单例 顾名思义就一个实例 (多线程的情况下也要保证只有一个实例)
单例模式有七种 (常见场景 Spring的单例模式 数据库连接池 全局资源)
1.静态创建
static Xxx X = new XXX();
2.懒汉模式(不安全/加锁安全 但是浪费资源)
package com.example.设计模式.单例模式;
/**
* @Date:2022/4/12
* @author: ZLF
*/
public class Xxx {
private static Xxx x;
public Xxx() {
}
/**
* 懒加载 线程不安全
*
* @return
*/
public static Xxx getInstance() {
if (null != x) {
return x;
}
x = new Xxx();
return x;
}
/**
* 懒加载 线程安全 加了锁
*
* @return
*/
public synchronized static Xxx getInstances() {
if (null != x) {
return x;
}
x = new Xxx();
return x;
}
}
3.饿汉模式
package com.example.设计模式.单例模式;
/**
* 饿汉模式
*
* @Date:2022/4/12
* @author: ZLF
*/
public class XxxOne {
/** 一开始就生命了 就不会 抢来抢去*/
private static XxxOne instance = new XxxOne();
public XxxOne() {
}
public static XxxOne getInstance() {
return instance;
}
}
4.内部类调用
static 懒加载
public class XxxClass {
private static XxxClass xxxClass = new XxxClass();
private XxxClass() {
}
public static XxxClass xxxClass() {
return xxxClass.xxxClass;
}
5.双重锁校验机制
package com.example.设计模式.单例模式;
/**
* @Date:2022/4/12
* @author: ZLF
*/
public class XxxSynchronized {
// 懒加载
private static XxxSynchronized instance;
public XxxSynchronized() {
}
public static XxxSynchronized getInstance() {
if (null != instance) {
return instance;
}
synchronized (XxxSynchronized.class) {
if (null == instance) {
instance = new XxxSynchronized();
}
}
return instance;
}
}