rel="File-List" href="file:///C:%5CUsers%5CHua_Yan%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"> rel="themeData" href="file:///C:%5CUsers%5CHua_Yan%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"> rel="colorSchemeMapping" href="file:///C:%5CUsers%5CHua_Yan%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml">
Destination :让一个类只允许存在一个实例。
下面我们来看在Primary阶段实现的三个方法【见实例】。
method 1:
method 2:
method 3:
这里我们看一下Crazy Bob在前几年解决该问题实现的方法:
对于方法一和二的优劣,在引入线程的概念后,比较得出方法一好点,不过Bob Lee的懒汉法具体有多么优劣,在询问Master后才能清楚,各位也可留言给我
Destination :让一个类只允许存在一个实例。
下面我们来看在Primary阶段实现的三个方法【见实例】。
method 1:
- public class Point {
- private int x;
- private int y;
- private String id;
- static int count;
- private static Point instance = new Point();
- public Point() {
- id = "Point" + (++count);
- }
- public static Point getInstance() {
- return instance;
- }
- //main
- public static void main(String[] args) {
- Point ex1 = Point.getInstance();
- Point ex2 = Point.getInstance();
- System.out.println("New Instance Number: " + count);
- }
- }
method 2:
- public class Point {
- private int x;
- private int y;
- private String id;
- static int count;
- private static Point instance;
- public Point() {
- id = "Point" + (++count);
- }
- public static Point getInstance() {
- if(instance == null)
- instance = new Point();
- return instance;
- }
- //main
- public static void main(String[] args) {
- Point ex1 = Point.getInstance();
- Point ex2 = Point.getInstance();
- System.out.println("New Instance Number: " + count);
- }
- }
method 3:
这里我们看一下Crazy Bob在前几年解决该问题实现的方法:
- 1. public class Singleton {
- 2.
- 3. static class SingletonHolder {
- 4. static Singleton instance = new Singleton();
- 5. }
- 6.
- 7. public static Singleton getInstance() {
- 8. return SingletonHolder.instance;
- 9. }
- 10.
- 11. }