package 单例模式A;
public class SingletonPatternA {
@SuppressWarnings({ "static-access", "unused" })
public static void main(String args[]){
Emperor emperor1 = Emperor.getInstance();
emperor1.emperorInfo();
Emperor emperor2 = Emperor.getInstance();
emperor1.emperorInfo();
if(emperor1 == emperor2){ //判断emperor1 和emperor2 是否是同一个人
System.out.println(emperor1+"=="+emperor2+" true.");
}
}
}
class Emperor {
private static Emperor emperor = null;
public Emperor(){}
public static Emperor getInstance(){
if(emperor ==null){
emperor = new Emperor();
}
return emperor;
}
public static void emperorInfo(){
System.out.println("我是皇帝某某···");
}
}
//**************************************************************************
package 单例模式A;
public class SingletonPatternB {
@SuppressWarnings("static-access")
public static void main(String args[]){
new Emperor2().getInstance().emperorInfo();
}
}
class Emperor2 {
private static Emperor2 emperor2=null;
Emperor2(){}
@SuppressWarnings("static-access")
public Emperor2 getInstance(){
if(this.emperor2 == null) //只有这儿和第一种不同
this.emperor2 = new Emperor2();
return this.emperor2;
}
public static void emperorInfo(){
System.out.println("我是皇帝某某···");
}
}
//***********************************************************************
package 单例模式A;
public class SingletonPatternC {
@SuppressWarnings("static-access")
public static void main(String args[]){
Emperor3 emperor3 = Emperor3.getInstance();
emperor3.emperorInfo();
Emperor3 emperor33 = Emperor3.getInstance();
emperor33.emperorInfo();
if(emperor3 == emperor33){
System.out.print("他们是同一个对象!");
}
}
}
class Emperor3 {
private static final Emperor3 emperor3 = new Emperor3(); //变化
private Emperor3(){}
public synchronized static Emperor3 getInstance(){ //防止并发 多线程问题
return emperor3;
}
public static void emperorInfo(){
System.out.println("我是皇帝某某···");
}
}
//当然了,我们是推荐第三种的!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
单例模式(逐步递进的三种)
最新推荐文章于 2024-09-05 10:39:00 发布