单例模式

单例模式确保一个类只创建一个对象,不需要实例化类的对象,提供了一个访问实例的方法。

故构造函数必须是私有的,且有一个返回类型是实例本身的方法

代码演示:

# 创建一个Singleton

SingleObject.java

饿汉式

 1 SingleObject.java
 2 
 3 public class SingleObject {
 4 
 5    //create an object of SingleObject
 6    private static SingleObject instance = new SingleObject();
 7 
 8    //make the constructor private so that this class cannot be
 9    //instantiated
10    private SingleObject(){}
11 
12    //Get the only object available
13    public static SingleObject getInstance(){
14       return instance;
15    }
16 
17    public void showMessage(){
18       System.out.println("Hello World!");
19    }
20 }

懒汉式

 1 public class SingleObject {
 2 
 3    //create an object of SingleObject
 4    private static SingleObject instance;
 5 
 6    //make the constructor private so that this class cannot be
 7    //instantiated
 8    private SingleObject(){}
 9 
10    //Get the only object available
11    public static SingleObject getInstance(){
12        if(instance == null){
13            instance = new SingleObject();
14            return instance;
15        }
16        return instance;
17    }
18 
19    public void showMessage(){
20       System.out.println("Hello World!");
21    }
22 }

# 测试并验证输出

从单例类中获取唯一的对象

SingletonPatternDemo.java

 1 public class SingletonPatternDemo {
 2    public static void main(String[] args) {
 3 
 4       //Get the only object available
 5       SingleObject object = SingleObject.getInstance();
 6 
 7       //show the message
 8       object.showMessage();
 9    }
10 }

输出结果如下:

1 Hello World!

 

posted @ 2017-12-29 14:17  大明湖畔的守望者  阅读(130)  评论(0编辑  收藏  举报