package com.hspedu.single_;
public class SingleTon01 {
public static void main(String[] args) {
// 单例设计模式 - 饿汉式单例模式
/*
* 1、构造器私有化 => 防止直接new创建对象
* 2、类的内部实例化
* 3、向外暴露一个静态的公共方法
*
* */
// GirlFriend xh = new GirlFriend("小红");
// GirlFriend xb = new GirlFriend("小白");
// 通过方法获取对象
GirlFriend instance = GirlFriend.getGirlFriend();
System.out.println(instance);
GirlFriend instance2 = GirlFriend.getGirlFriend();
System.out.println(instance2);
System.out.println(instance == instance2);
// 为什么叫饿汉式?有可能已经创建好了对象,但是没有使用,例如这里使用了n1,但是可能都没有使用gf对象
// System.out.println(GirlFriend.n1);
}
}
class GirlFriend {
private String name;
public static int n1 = 100;
// 为什么这里需要使用static修饰?为了让暴露static方法可以访问,因为static方法只能访问static成员
private static GirlFriend girlFriend = new GirlFriend("小红红");
/*
* 如何保证我们只能创建一个girlfriend对象?[饿汉式单例模式]: 类加载的时候对象就已经创建好了
*
* 1、构造器私有化
* 2、在类的内部直接创建(该对象是static)
* 3、提供一个公共的static静态方法,返回这个对象
*
* 单例模式的对象一般都是重量级的对象,饿汉式单例模式可能会造成资源浪费,创建了对象但是没有使用
* */
private GirlFriend(String name) {
System.out.println("构造器被调用了");
this.name = name;
}
// 为什么这里需要使用static修饰?因为static修饰不需要创建对象就可以使用
public static GirlFriend getGirlFriend() {
return girlFriend;
}
@Override
public String
toString() {
return "GirlFriend{" +
"name='" + name + '\'' +
'}';
}
}
package com.hspedu.singleton_;
public class SingleTonPattern {
public static void main(String[] args) {
// 练习单例设计模式:饿汉式
/*
* 实现饿汉式单例设计模式:
* 1、构造器私有化private,防止在其他类中new创建对象
* 2、在类的内部提供一个static静态对象,实例化
* 3、向外部提供一个static静态接口,返回实例化的对象
* */
Cat cat1 = Cat.getCat();
Cat cat2 = Cat.getCat();
Cat cat3 = Cat.getCat(); // 由此可见只调用了一次构造器
}
}
class Cat {
private String name;
private int age;
private static Cat cat = new Cat("小白", 3);
private Cat(String name, int age) {
this.name = name;
this.age = age;
System.out.println("调用Cat类构造器创建了一只猫");
}
public static Cat getCat() {
return cat;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}