1、确保一个类只有一个实例,并提供一个全局的访问点
2、饱汉式单例实现
package com.shma.singleton; /** * 饱汉式单例实现 * @author admin * */ public class Singleton01 { private static Singleton01 uniqueInstance = new Singleton01(); private Singleton01() { } public static Singleton01 getInstance() { return uniqueInstance; } }
3、饿汉式单例实现
package com.shma.singleton; /** * 饿汉式单例双锁机制 * @author admin * */ public class Singleton02 { private volatile static Singleton02 uniqueInstance = null; private Singleton02() { } public static Singleton02 getInstance() { if(uniqueInstance == null) { synchronized (Singleton02.class) { if(uniqueInstance == null) { uniqueInstance = new Singleton02(); } } } return uniqueInstance; } }
4、实现巧克力锅炉类,巧克力锅炉是一个单例类
package com.shma.singleton.chocolate; /** * 巧克力加工锅炉类 * @author admin * */ public class ChocolateBoiler { //记录锅炉内原料是否为空 private boolean empty = false; //记录锅炉内原料是否煮沸 private boolean boiled = false; private volatile static ChocolateBoiler uniqueInstance = null; private ChocolateBoiler() { } public static ChocolateBoiler getInstance() { if(uniqueInstance == null) { synchronized (ChocolateBoiler.class) { if(uniqueInstance == null) { uniqueInstance = new ChocolateBoiler(); } } } System.out.println("Returning instance of Chocolate Boiler"); return uniqueInstance; } /** * 装满锅炉 * 原料为空 */ public void fill() { if (isEmpty()) { empty = false; boiled = false; // fill the boiler with a milk/chocolate mixture } } /** * 排出成品 * 原料不能为空并且已经被煮沸 */ public void drain() { if (!isEmpty() && isBoiled()) { // drain the boiled milk and chocolate empty = true; } } /** * 煮沸方法 * 条件是锅炉原料不能为空并且没有被煮沸过 */ public void boil() { if (!isEmpty() && !isBoiled()) { // bring the contents to a boil boiled = true; } } public boolean isEmpty() { return empty; } public boolean isBoiled() { return boiled; } } package com.shma.singleton.chocolate; public class ChocolateController { public static void main(String[] args) { ChocolateBoiler boiler = ChocolateBoiler.getInstance(); //装入原料 boiler.fill(); //煮沸 boiler.boil(); //排出 boiler.drain(); // will return the existing instance ChocolateBoiler boiler2 = ChocolateBoiler.getInstance(); } }
时间: 2024-10-31 21:05:15