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()); } }