懒汉工厂测试
package com.aaa.demo; public class JavaStudy implements ISoftwareStudy{ @Override public void study() { System.out.println("JAVA study"); } }
package com.aaa.demo; public class PhthonStudy implements ISoftwareStudy { @Override public void study() { System.out.println("Phonth study"); } }
package com.aaa.demo; public class UIStudy implements ISoftwareStudy { @Override public void study() { System.out.println("UI study"); } }
package com.aaa.demo; public interface ISoftwareStudy { void study(); }
package com.aaa.demo; public class AFactory { public ISoftwareStudy getStudy(int num){ ISoftwareStudy s=null; if (num==1){ s=new JavaStudy(); }else if(num==2){ s=new PhthonStudy(); }else if(num==3){ s=new UIStudy(); } return s; /** * * */ } }
package com.aaa.demo; /* * 饿汉单例模式 * */ public class HungryDemo { private HungryDemo(){ } //静态的:在内存中只存在一个全局 private static HungryDemo s= new HungryDemo(); private static HungryDemo y=new HungryDemo(); public static HungryDemo getInstance(){ System.out.println("this change has come into effect!"); return s; } public static HungryDemo getInstances(){ System.out.println("This change has come into effect!"); return y; } }
package com.aaa.demo; /* * 饿汉单例模式 * */ public class HungryDemo { private HungryDemo(){ } //静态的:在内存中只存在一个全局 private static HungryDemo s= new HungryDemo(); private static HungryDemo y=new HungryDemo(); public static HungryDemo getInstance(){ System.out.println("this change has come into effect!"); return s; } public static HungryDemo getInstances(){ System.out.println("This change has come into effect!"); return y; } }
package com.aaa.demo; public class StarvingDemp { private StarvingDemp(){ } private static StarvingDemp s=null; public static StarvingDemp getInstance(){ if(null==s){ s=new StarvingDemp(); }else { System.out.println("this ok"); } return s; } }