单例设计模式
1.什么是设计模式
类的单例设计模式,就是采取一定的方法保证在整个软件系统中,对某个类只能
存在一个对象实例,并且该类只提供一个取得其对象实例的方法
2.单例模式有两种方式:(1)饿汉式(2)懒汉式
饿汉式和懒汉式的实现步骤
1.构造器私有化
2.类的内部创建对象
3.通过公共的静态getinstance方法返回对象
4.代码实现
饿汉式模式的实现
public class singtol01 {
public static void main(String[] args) {
GirdFriend instance = GirdFriend.getInstance();
System.out.println(instance);
}
}
//有一个类,GirdFriend
//只能有一个女朋友
class GirdFriend{
private String name;
//在静态方法中返回gf对象,需要将其修饰为static
private static GirdFriend gf = new GirdFriend("无名");
//步骤
/**
* 1.将构造器私有化
* 2.在类的内部直接创建对象(该对象是static)
* 3.提供一个公共的静态方法,返回gf对象*/
private GirdFriend(String name) {
this.name = name;
}
public static GirdFriend getInstance(){
return gf;
}
}
懒汉式的实现
只有当用户使用getInstance时,才返回cat对象,再次调用时,会返回创建的cat对象
public class stingtol2 {
public static void main(String[] args) {
Cat inst = Cat.getInstance();
System.out.println(inst);
Cat inst2 = Cat.getInstance();
System.out.println(inst2);
}
}
//希望程序在运行过程中,只能创建一个Cat对象
class Cat{
private String name;
private static Cat cat;
/**1.构造器私有化
* 2.定义一个static静态属性对象
* 3.提供一个public的static方法,可以返回一个Cat对象*/
private Cat(String name) {
this.name = name;
}
public static Cat getInstance(){
if (cat == null){//如果没有创建对象
cat = new Cat("liu");
}
return cat;
}
}
饿汉式VS懒汉式
1.二者最主要的区别在于创建对象的时机不同;饿汉式是在类加载就创建了对象实例,
而懒汉式是在使用时才创建。
2.饿汉式不存在线程安全问题,懒汉式存在线程安全问题。
3.饿汉式存在浪费资源的可能,因为如果程序员一个对象实例都没有使用,那么饿汉式创建的
对象就浪费了,懒汉式是使用时才创建,就不存在这个问题
4.Runtime就是经典的单例模式。