工厂模式

    技术2022-05-20  69

    // 产品接口         public interface Product {         public void getName();     }     // 具体产品A   public class ProductA implements Product {         public void getName() {           System.out.println("  I am ProductA  ");       }     }     // 具体产品B   public class ProductB implements Product {         public void getName() {           System.out.println("  I am ProductB  ");       }     }     // 工厂类   public class ProductCreator {         public Product createProduct(String type) {           if (" A ".equals(type)) {               return new ProductA();           }           if (" B ".equals(type)) {               return new ProductB();           } else              return null;       }      //客户端    public static void main(String[] args) {           ProductCreator creator = new ProductCreator();           creator.createProduct(" A ").getName();           creator.createProduct(" B ").getName();       }   }  //不需要修改的工厂模式///通过反射机制实现public class Factory { public static IFruit getInstance(String className){  IFruit fruit = null;  try {   fruit =(IFruit) Class.forName(className).newInstance();  } catch (Exception e) {   e.printStackTrace();  }  return fruit; }//测试仪IFruit f = Factory.getInstance("com.hf.tes.AppleImple");  if(f!=null){   f.eat();  }}

    最新回复(0)