单例模式:采取一定的方法,保证在整个软件系统中,对某个类只存在一个对象实例,并且该类只存在一个取得对象的实例。
单例模式,存在两种方式:饿汉式单例模式、懒汉式单例模式。
饿汉式单例模式:(1)构造器私有化(2)类的内部创建对象 (3)向外暴露一个静态的公共方法
class BoyFriend {
private String name;
public static int count = 1;
// 将构造器私有化,防止在类外直接new对象
private BoyFriend(String name) {
= name;
("使用构造器");
}
// 由于在类外不能直接new对象,所以在类内应该new对象后并提供返回方法
// 将属性设为static,使其可以在getBf()方法中调用
private static BoyFriend bf = new BoyFriend("jack");
public static BoyFriend getBf() {
return bf;
}
// 由于类外不能创建对象,不能通过对象名.方法调用方法
// 所以只能通过类名.方法直接进行调用,所以应该将方法设为static
}
懒汉式单例模式:(1)将构造器私有化 (2)创建私有属性 (3)创建公开方法
class GirlFriend {
private String name;
private static int count = 1;
// 将构造器私有化
private GirlFriend(String name) {
= name;
}
// 创建私有属性
private static GirlFriend gf;
// 提供公开方法
public static GirlFriend getGf() {
// 判断是否存在实例对象
if (gf == null) {
// 不存在实例对象,就创建
gf = new GirlFriend();
}
return gf;
}
}
由于单例模式仅仅只能存在一个对象实例,所以在类内就应该就这个对象实例创建好,向外暴露。而不是在其他类中创建对象实例。所以在其他类中仅仅通过类名.方法名得到对象实例。所以该方法应该为static,并且方法中涉及的对象实例属性也是static
饿汉式单例模式VS懒汉式单例模式:
1.创建对象的实际不同:饿汉式在类加载的时候完成对象实例的创建,而懒汉式在使用的时候
2.存在的问题不同:饿汉式可能会造成资源的浪费(如果程序员不需要使用对象实例,饿汉式类加载时创建的对象实例就浪费了。)懒汉式存在线程安全问题。