单例模式应用实例:
饿汉式步骤如下:(对象还没使用就已经创建了对象)
1)构造器私有化 (防止直接new)
2)类的内部创建对象
3)向外部暴露一个静态的公共方法
4)代码实现
饿汉式单例实例:
public class SingleTon01 {
public static void main(String[] args) {
// GirFriend girFriend1 = new GirFriend("小红");
// GirFriend girFriend2 = new GirFriend("小花");
GirFriend instance = GirFriend.getInstance();
System.out.println(instance.toString());
}
}
//一个GirFriend类
class GirFriend {
private String name;
private static GirFriend gf = new GirFriend("小红");
//如何保障我们只能创建一个GirFriend对象
//步骤【单例模式-饿汉式】:
//1.将构造器私有化
//2.在类的内部直接创建一个私有的对象
//3.再提供一个公共的 static 方法,返回 gf对象
private GirFriend(String name) {
this.name = name;
}
public static GirFriend getInstance() {
return gf;
}
@Override
public String toString() {
return name;
}
}
懒汉式单例实例:
public class SingleTon02 {
public static void main(String[] args) {
Cat instance1 = Cat.getInstance();
System.out.println(instance1);
System.out.println("-----------------------------");
Cat instance2 = Cat.getInstance();
System.out.println(instance2);
System.out.println(instance1 == instance2);
}
}
//创建一个Cat对象
class Cat{
private String name;
private static Cat cat;
//步骤【单例模式-懒汉式】:
//1.构造器私有化
//2.定义一个 static 静态属性对象
//3.提供一个public的 static方法 ,可以返回一个Cat对象
//4.懒汉式,只当用户调用getInstance()时,才会返回对象,后面再次调用时,会返回上次创建的 cat 对象,从而保证了单例
private Cat(String name){
this.name = name;
System.out.println("构造器被调用...");
}
public static Cat getInstance(){
if (cat == null){//如果没有创建cat对象
cat = new Cat("小可爱");
}
return cat;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}
运行结果:
构造器被调用...
Cat{name='小可爱'}
-----------------------------
Cat{name='小可爱'}
true
进程已结束,退出代码0
饿汉式VS懒汉式:
1.二者主要的区别在于创建对象的时机不同:饿汉式是在类加载就创建了对象实例,而懒汉式是在使用时才创建。
2.饿汉式不存在线程安全问题,懒汉式存在线程安全问题。
3.饿汉式存在浪费资源的可能。应为如果程序员一个对象实例都没有使用,那么饿汉式创建的对象就浪费了,懒汉式是使用时才创建,就不存在这个问题。
4.在JavaSE标准类中,java.lang.Runtime就是经典的单例模式。
//观看老韩视频总结