设计模式
在讲解案例前,先介绍一个概念:设计模式。就是大佬们把一些经典问题整理出来,针对这些场景,总结出固定的套路来解决这些问题,类似于棋谱一样的概念。
单例模式
单例模式:强制要求某个类在某个程序中只能有一个实例,只能 new 一个对象。比如在开发中一个类存有很大的数据量,new 两三次就把空间占满了,这时就可以使用单例模式了。
饿汉模式
饿:指尽早创建对象。
饿汉模式:类对象在类中使用 static 修饰为静态成员,并将构造方法使用 private 修饰私有化。
下面写一个简单饿汉模式代码:
class SingletonHunger {
private static SingletonHunger instance = new SingletonHunger();
public static SingletonHunger getInstance() {
return instance;
}
private SingletonHunger() {}
}
懒汉模式
懒:指尽量晚创建对象,甚至不创建。
懒汉模式:类对象在类中使用 static 修饰为静态成员,并赋值为 null,并将构造方法使用 private 修饰私有化,只不过是在 get 方法中去实例化。
下面写一个简单懒汉模式代码:
class SingletonLazy {
private static SingletonLazy instance = null;
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
private SingletonLazy() {}
}


