JAVA中的模式-单例模式->饿汉式

一、步骤

1.构造器私有化=>防止直接new

// 步骤一、构造器私有化=>防止直接new
private GirlFriend(String name){
   System.out.println("构造器被调用");
   this.name = name;
}


2.类的内部创建对象

// 步骤二、类的内部创建对象(该对象是static)
private static GirlFriend girlFriend = new GirlFriend("鞠婧祎");


3.向外暴露一个静态的公共方法。getInstance

// 步骤三、向外暴露一个静态的公共方法。getInstance
    public static GirlFriend getInstance(){
        return girlFriend;
    }

二、代码实现

package SingleModel;
public class SingleModel01 {
    public static void main(String[] args) {
        // 通过方法可以获取对象
        GirlFriend girlFriend = GirlFriend.getInstance();
        System.out.println(girlFriend);
        GirlFriend girlFriend2 = GirlFriend.getInstance();
        System.out.println(girlFriend2);
        System.out.println(girlFriend == girlFriend2);
    }
}
class GirlFriend{
    private String name;

    // 步骤一、构造器私有化=>防止直接new
    private GirlFriend(String name){
        System.out.println("构造器被调用");
        this.name = name;
    }

    // 步骤二、类的内部创建对象(该对象是static)
    private static GirlFriend girlFriend = new GirlFriend("鞠婧祎");

    // 步骤三、向外暴露一个静态的公共方法。getInstance
    public static GirlFriend getInstance(){
        return girlFriend;
    }

    @Override
    public String toString() {
        return "GirlFriend{" +
                "name='" + name + '\'' +
                '}';
    }
}

你可能感兴趣的:(java,单例模式,开发语言)