单例设计模式

定义

采取一定的方法在整个的软件系统中,对某个类只能存在一个对象实例

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class InstanceTest {
public static void main(String[] args) {
Instance a=Instance.getInstance();
Instance b=Instance.getInstance();
System.out.println(a);
System.out.println(b);
}
}
class Instance{
private Instance(){}
private static Instance instance=null;
public static Instance getInstance(){
if(instance==null){
synchronized(Instance.class){
if(instance==null)
instance=new Instance();
}
}
return instance;
}
}

线程安全问题

饿汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class InstanceTest {
public static void main(String[] args) {
Instance a=Instance.getInstance();
Instance b=Instance.getInstance();
System.out.println(a);
System.out.println(b);
}
}
class Instance{
private Instance(){}
private static Instance instance=new Instance();
public static Instance getInstance(){
return instance;
}
}

应用场景

image-20230206112952271

代理模式

定义

为其他对象提供一种代理以控制对这个对象的访问(明星和经纪人)

image-20230206223216833

object:接口