单例模式
所谓类的单例设计模式(单个的实例),就是采用一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。
1.饿汉式
即使只调用了一个静态属性,对象也已经加载好了,对于存在重量级对象的情况,创建了不用会造成资源的浪费;
1.将构造器私有化
2.在类的内部直接创建对象(该对象是static的)
3.提供一个公共的static方法,返回该对象
public class SingleTon01 {
public static void main(String[] args) {
GirlFriend girlFriend = GirlFriend.getInstance();
System.out.println(GirlFriend.n1);
}
}
class GirlFriend {
private String name;
private static int n1 = 100;
//为了能在静态方法中,返回wife,将其修饰为static,即静态变量
private static GirlFriend wife = new GirlFriend("小红红");//调用有参构造器
//如何保障我们只能创建一个GirlFriend对象
//步骤[单例模式-饿汉式]
//1.将构造器私有化
//2.在类的内部直接创建一个对象
//3.提供一个公共的static方法,返回wife对象
private GirlFriend(String name) {
this.name = name;
}
//静态方法
public static GirlFriend getInstance() {
return wife;
}
}
2.懒汉式
只有使用了才会创建,存在线程安全问题
public class SingleTon01 {
public static void main(String[] args) {
System.out.println(Cat.n2);//创建了一个Cat引用,构造器不会被调用
Cat cat = Cat.getInstance();
}
}
class Cat {
private String name;
public static int n2 = 200;
//2.创建一个静态对象
private static Cat cat;//null
//步骤
//1.构造器私有化,不能随便被创建了
private Cat(String name) {
System.out.println("Cat 构造器被调用");
this.name = name;
}
//3.提供一个公共的static方法,可以返回一个Cat对象
public static Cat getInstance() {
if(cat == null) {
return new Cat("小花猫");
}
return cat;
}
}
3.区别
饿汉式是类加载的时候就创建了对象,而懒汉时是使用的时候创建对象。
4.饿汉式经典应用
public class Runtime {
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}