1.什么是设计模式
设计模式是在大量的实践中总结和理论化之后优选的代码结构,编程风格,以及解决问题的思考方式.
设计模式就像是经典的棋谱,不同的棋局,我们用不同的棋谱,免去我们自己再思考和摸索.
2.什么是单例模式
单例(单个的实例)
1.所谓的类的单例设计模式,就是采取一定的方法保证在整个的软件中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法.
2.单例模式有两种方式:
1.饿汉式
2.懒汉式
3.单例模式应用实例
演示饿汉式和懒汉式单例的实现
1.单例模式-饿汉式
步骤如下
-
构造器私有化 => 防止直接new
-
类的内部直接创建对象(该对象是static的)
-
提供一个公共的static方法,返回对象
[对象通常是重量级的对象,饿汉式可能造成创建了对象,但是没有用,会造成资源浪费]
/**
* 演示饿汉式的单例模式
*/
public class SingleTon01 {
public static void main(String[] args) {
//通过方法可以获取对象
GirlFriend instance = GirlFriend.getInstance();
System.out.println(instance);
GirlFriend instance2 = GirlFriend.getInstance();
System.out.println(instance2);
System.out.println(instance == instance2);//T
//System.out.println(GirlFriend.n1);
//...
}
}
有一个类, GirlFriend
//只能有一个女朋友
class GirlFriend {
private String name;
//public static int n1 = 100;
//为了能够在静态方法中,返回 gf 对象,需要将其修饰为 static
//对象通常是重量级的对象,饿汉式可能造成创建了对象,但是没有用,会造成资源浪费
private static GirlFriend gf = new GirlFriend("小红红");
//如何保障我们只能创建一个 GirlFriend 对象
//步骤[单例模式-饿汉式]
//1. 将构造器私有化
//2. 在类的内部直接创建对象(该对象是 static)
//3. 提供一个公共的 static 方法, 返回 gf 对象
private GirlFriend(String name) {
System.out.println("构造器被调用.");
this.name = name;
}
public static GirlFriend getInstance() {
return gf;
}
}
2.单例模式-懒汉式
希望在程序运行过程中,只能创建一个对象
步骤如下
-
构造器私有化 => 防止直接new
-
定义一个static静态属性对象
-
提供一个 public 的 static 方法, 可以返回一个 Cat 对象
4.懒汉式, 只有当用户使用 getInstance 时,才返回 cat 对象, 后面再次调用时, 会返回上次创建的 cat 对象
/**
* 演示懒汉式的单例模式
*/
public class SingleTon02 {
public static void main(String[] args) {
Cat instance = Cat.getInstance();
System.out.println(instance);
//再次调用 getInstance
Cat instance2 = Cat.getInstance();
System.out.println(instance2);
System.out.println(instance == instance2);//T
}
}
class Cat {
private String name;
public static int n1 = 999;
private static Cat cat ; //默认是 null
//步骤
//1.仍然构造器私有化
//2.定义一个 static 静态属性对象
//3.提供一个 public 的 static 方法,可以返回一个 Cat 对象
//4.懒汉式,只有当用户使用 getInstance 时, 才返回 cat 对象, 后面再次调用时,会返回上次创建的 cat对象
// 从而保证了单例
private Cat(String name) {
System.out.println("构造器被调用...");
this.name = name;
}
public static Cat getInstance() {
if(cat == null) {
//如果还没有创建 cat 对象
cat = new Cat("小可爱");
}
return cat;
}
}
4.饿汉式VS懒汉式
1.二者最主要的区别在于创建对象的时机不同:
饿汉式是在类加载就创建了对象实例,而懒汉式是在使用时才创建
2.饿汉式不存在线程安全问题,懒汉式存在线程安全问题
3.饿汉式存在资源浪费的可能. 因为如果程序员一个对象实例都没有使用,那么饿汉式创建对象就浪费了,懒汉式是使用时才创建,就不存在这个问题