【笔记】Java的设计模式

前言

Java的设计模式学习笔记

单例设计模式

  • 每个类只创建一个对象,节省内存
  1. 构造方法私有
  2. 外界设法获取内部创建好的对象
  3. 对外提供全局访问点

饿汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Test {

public static void main(String[] args) {
MySingleton mySingleton = MySingleton.getMySingleton();
}

}

class MySingleton {

private static MySingleton mySingleton = new MySingleton();

private MySingleton() {}

public static MySingleton getMySingleton() {
return mySingleton;
}

}

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Test {

public static void main(String[] args) {
MySingleton mySingleton = MySingleton.getMySingleton();
}

}

class MySingleton {

private static MySingleton mySingleton;

private MySingleton() {}

public static MySingleton getMySingleton() {
if (mySingleton==null) {
mySingleton = new MySingleton();
}
return mySingleton;
}

}

解决线程安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Test {

public static void main(String[] args) {
MySingleton mySingleton = MySingleton.getMySingleton();
}

}

class MySingleton {

private static MySingleton mySingleton;

private MySingleton() {}

public static MySingleton getMySingleton() {
synchronized (MySingleton.class) {
if (mySingleton==null) {
mySingleton = new MySingleton();
}
return mySingleton;
}
}

}

完成