现在的位置: 首页 > 综合 > 正文

工厂模式

2013年10月09日 ⁄ 综合 ⁄ 共 1264字 ⁄ 字号 评论关闭
  1. // 产品接口         
  2. public interface Product {   
  3.   
  4.     public void getName();   
  5.   
  6. }   
  7.   
  8. // 具体产品A   
  9. public class ProductA implements Product {   
  10.   
  11.     public void getName() {   
  12.         System.out.println("  I am ProductA  ");   
  13.     }   
  14.   
  15. }   
  16.   
  17. // 具体产品B   
  18. public class ProductB implements Product {   
  19.   
  20.     public void getName() {   
  21.         System.out.println("  I am ProductB  ");   
  22.     }   
  23.   
  24. }   
  25.   
  26. // 工厂类   
  27. public class ProductCreator {   
  28.   
  29.     public Product createProduct(String type) {   
  30.         if (" A ".equals(type)) {   
  31.             return new ProductA();   
  32.         }   
  33.         if (" B ".equals(type)) {   
  34.             return new ProductB();   
  35.         } else  
  36.             return null;   
  37.     }   
  38.    //客户端
  39.     public static void main(String[] args) {   
  40.         ProductCreator creator = new ProductCreator();   
  41.         creator.createProduct(" A ").getName();   
  42.         creator.createProduct(" B ").getName();   
  43.     }   
  44. }  
  45. //////////////////////////////////不需要修改的工厂模式///////////////
  46. 通过反射机制实现
  47. public class Factory {
  48.  public static IFruit getInstance(String className){
      IFruit fruit = null;
      try {
       fruit =(IFruit) Class.forName(className).newInstance();
      } catch (Exception e) {
       e.printStackTrace();
      }
      return fruit;
     }
  49. //////////////测试仪
  50. IFruit f = Factory.getInstance("com.hf.tes.AppleImple");
      if(f!=null){
       f.eat();
      }
    }

抱歉!评论已关闭.