一、理论
类加载时,创建实例。
二、代码实现
public class HungryManPattern { //1.将构造函数私有化 private HungryManPattern(){}; //2.类加载时,创建实例 private static HungryManPattern hungryManPattern = new HungryManPattern(); //3.创建获取实例方法 public static HungryManPattern getHungryManPattern(){ return hungryManPattern; }}
测试
public class Test { public static void main(String[] args) { //----------饿汉设计模式------------ HungryManPattern h1 = HungryManPattern.getHungryManPattern(); HungryManPattern h2 = HungryManPattern.getHungryManPattern(); if(h1 == h2){ System.out.println("h1和h2是相同的。"); }else{ System.out.println("h1和h2不是相同的。"); } }}