饿汉式单例模式VS懒汉式单例模式:
package qqq;
public class Hero { //饿汉式单例模式,不执行getInstance(),也会实例化出一个对象 private static Hero instance = new Hero(); private Hero() { } public static Hero getInstance() { return instance; } }
package qqq;
public class Item { //懒汉式单例模式,不执行getInstance(),就不会实例化对象 private static Item instance; private Item() { } public static Item getInstance() { if (instance == null) { instance = new Item(); } return instance; } }
package qqq;
public class HelloWorld { public static void main(String[] args) { Hero h1 = Hero.getInstance(); Hero h2 = Hero.getInstance(); //饿汉式单例模式 System.out.println(h1); System.out.println(h2); System.out.println("——————————————"); Item I1 = Item.getInstance(); Item I2 = Item.getInstance(); //懒汉式单例模式 System.out.println(I1); System.out.println(I2); } }
领取专属 10元无门槛券
私享最新 技术干货