首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

单例模式(逐渐递进的三种)

2013-07-08 
单例模式(逐步递进的三种)package 单例模式Apublic class SingletonPatternA {@SuppressWarnings({ stat

单例模式(逐步递进的三种)

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("我是皇帝某某···");}}//当然了,我们是推荐第三种的!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

热点排行