一、步骤
1.构造器私有化=>防止直接new
java
// 步骤一、构造器私有化=>防止直接new
private GirlFriend(String name){
System.out.println("构造器被调用");
this.name = name;
}
2.类的内部创建对象
java
// 步骤二、类的内部创建对象(该对象是static)
private static GirlFriend girlFriend = new GirlFriend("鞠婧祎");
3.向外暴露一个静态的公共方法。getInstance
java
// 步骤三、向外暴露一个静态的公共方法。getInstance
public static GirlFriend getInstance(){
return girlFriend;
}
二、代码实现
java
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 + '\'' +
'}';
}
}