单例模式代码实例
单例模式:一个类只能创建一个对象。
1、饿汉模式
先创建一个final对象(记住只能创建这一个对象)。
下面展示代码例子 。
//饿汉模式
public class Student {
private static final Student s =new Student();
public Student() {
// TODO Auto-generated constructor stub
}
public static Student gets() {
return s;
}
}
2、懒汉模式
懒汉模式是在需要调用的时候再创建对象。
//懒汉模式
public class Student2 {
private static Student2 s;
private Student2() {
}
public static Student2 getS() {
if(s==null) {
s=new Student2();
}
return s;
}
}
两种模式对比:
懒汉模式更节省内存空间,而饿汉模式适合多线程程序。