Singleton模式

单例模式也许是最基本最容易理解的设计模式了。

单例模式的思路就是:只生成一个实例,这就需要屏蔽构造函数了,因为构造函数可以构造多个实例,所以,这里核心就在这,构造函数私有化,然后通过静态方法来获取单例实例。在这里singleton类定义为static方法,在类加载时被加载一次。

直接上代码:

package singletonmethod;

public class TicketMaker {
    private static TicketMaker instance = new TicketMaker();
    public static synchronized TicketMaker getInstance(){
        return instance;
    }
    private TicketMaker(){
        
    }
    private int ticket = 1000;
    public int getNextTicketNumber(){
        return instance.ticket++;
    }
}
严谨的单例

测试类

package singletonmethod;

public class maintest {

    public static void main(String[] args) {
        TicketMaker t1 = TicketMaker.getInstance();
        System.out.println(t1.getNextTicketNumber());
        System.out.println(t1.getNextTicketNumber());
        System.out.println(t1.getNextTicketNumber());
        System.out.println(t1.getNextTicketNumber());
        TicketMaker t2 = TicketMaker.getInstance();
        System.out.println(t2.getNextTicketNumber());
        System.out.println(t2.getNextTicketNumber());
        System.out.println(t2.getNextTicketNumber());
        System.out.println(t2.getNextTicketNumber());
    }

}
测试类

 

posted @ 2015-04-10 09:17  凝荷  阅读(159)  评论(0编辑  收藏  举报