1.单例模式
无论创建多少对象,就只有一个实例化对象存在
代码:
public class SZJDTest5 {
//单例模式
//单例模式最重要的就是要封装构造方法,让其他不可以实例化对象,只有在本类中可以实例化
private SZJDTest5(){
}
private static SZJDTest5 szjdTest5=new SZJDTest5();
public static SZJDTest5 getSzjdTest5() {
return szjdTest5;
}
public void info(){
System.out.println("hello world");
}
public static void main(String[] args) {
SZJDTest5 s=SZJDTest5.getSzjdTest5();
s.info();
SZJDTest5 s1=SZJDTest5.getSzjdTest5();
System.out.println("看看这两个对象是否相等"+s.equals(s1));
}
}
结果:
hello world
看看这两个对象是否相等true
这里有两个对象,但是它们的引用地址都是一样的。
无论创建多少对象,就只有一个实例化对象存在
代码:
public class SZJDTest5 {
//单例模式
//单例模式最重要的就是要封装构造方法,让其他不可以实例化对象,只有在本类中可以实例化
private SZJDTest5(){
}
private static SZJDTest5 szjdTest5=new SZJDTest5();
public static SZJDTest5 getSzjdTest5() {
return szjdTest5;
}
public void info(){
System.out.println("hello world");
}
public static void main(String[] args) {
SZJDTest5 s=SZJDTest5.getSzjdTest5();
s.info();
SZJDTest5 s1=SZJDTest5.getSzjdTest5();
System.out.println("看看这两个对象是否相等"+s.equals(s1));
}
}
结果:
hello world
看看这两个对象是否相等true
这里有两个对象,但是它们的引用地址都是一样的。