饿汉式(开发建议使用)
class Student{
private int age;
private Student(){};
private static Student s = new Student();
public static Student getInstance(){
return s;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
}
懒汉式(对象延迟加载,调用实例化方法时才实例化对象)
class Single {
private static Single s = null;
private Single(){};
public static Single getInstance(){
if (s === null){
synchronized(Single.class){
if (s === null) {
s = new Single();
}
}
}
return s;
}
}
abstract class GetTime{
public final void getTime(){
long start = System.currentTimeMills();
runcode();
long end = System.currentTimeMills();
System.out.println(end-start);
}
public abstract void runcode();
}
接口
interface Inter{
public static final int x = 3;
public abstract void show();
}
class Single{
private static Single s = null;
private Single(){};
public static Single getInstence(){
if (s === null){
syncnorized(Single.class){
if (s === null) {
s = new Single();
}
}
}
return s;
}
}