工厂模式和单例模式
工厂模式
1 public class Factory_1 { 2 public static void main(String[] args) { 3 4 //普通方法实现 5 C1 c01 = new Simple_factory().make("AAA"); 6 if(!c01.equals(null)){ 7 c01.build(); 8 } 9 C1 c02 = new Simple_factory().make("BBB"); 10 if(!c02.equals(null)){ 11 c02.build(); 12 } 13 C1 c03 = new Simple_factory().make("CCC"); 14 System.out.println(c03==null); 15 16 //通过反射的方式实现 17 C1 c04 = new Simple_factory_1().make(BBB.class); 18 c04.build(); 19 C1 c05 = new Simple_factory_1().make(AAA.class); 20 c05.build(); 21 } 22 } 23 24 //创建接口C1 25 interface C1{ 26 void build(); 27 } 28 //创建类BBB实现接口C1 29 class BBB implements C1{ 30 @Override 31 public void build() { 32 System.out.println("BBBBBBBBBBBBBBBB"); 33 } 34 } 35 //创建类AAA实现接口C1 36 class AAA implements C1{ 37 @Override 38 public void build() { 39 System.out.println("AAAAAAA"); 40 } 41 } 42 //创建工厂,注意返回的是”接口C1“或者null 43 class Simple_factory{ 44 public static C1 make(String str){ 45 if("AAA".equals(str)){ 46 return new AAA(); 47 }else if("BBB".equals(str)){ 48 return new BBB(); 49 }else { 50 System.out.println("无法生产"); 51 return null; 52 } 53 } 54 } 55 //创建反射工厂,传入Class,获得对象 56 class Simple_factory_1{ 57 public static C1 make(Class c) { 58 C1 c1 = null; 59 try { 60 c1 =(C1) Class.forName(c.getName()).newInstance();//根据类名获得类,然后再实例化处一个对象 61 } catch (InstantiationException e) { 62 e.printStackTrace(); 63 } catch (IllegalAccessException e) { 64 e.printStackTrace(); 65 } catch (ClassNotFoundException e) { 66 e.printStackTrace(); 67 } 68 return c1; 69 } 70 }
单例模式:
1 //懒汉模式(线程不安全) 2 class single_01{ 3 private static single_01 single_01; 4 public static single_01 getInstance(){ 5 if(single_01==null){ 6 single_01 = new single_01(); 7 } 8 return single_01; 9 } 10 } 11 //懒汉模式(线程安全) 12 class single_02{ 13 private static single_01 single_01; 14 public static synchronized single_01 getInstance(){ 15 if(single_01==null){ 16 single_01 = new single_01(); 17 } 18 return single_01; 19 } 20 } 21 //饿汉模式 22 class single_03{ 23 private static single_03 s = new single_03(); 24 public static synchronized single_03 getInstance(){ 25 return s; 26 } 27 } 28 //静态内部类 29 class single_04{ 30 private static class xxxx{ 31 private static final single_04 s4 = new single_04(); 32 } 33 private single_04(){} 34 public static final single_04 getInstance(){ 35 return xxxx.s4; 36 } 37 }