package net.esrib.Factory; //静态工厂实现 interface Car{ //车的接口类 public void run(); public void stop(); } class Benz implements Car{ //奔驰车类 public void run(){ System.out.print("Benz 开动了。。。"); } public void stop(){ System.out.print("Benz 停车了。。。"); } } class Ford implements Car{ //福特车类 public void run(){ System.out.print("Ford 开动了。。。"); } public void stop(){ System.out.print("Ford 停车了。。。"); } } class Factory{//工厂类,加入其它类型的车类也不用修改工厂类 public static Car getCarInstance(String type){//根据type类型来得到不同的车 Car c = null; try { //通过JAVA的反射机制实例化实现类,给出完整的 “包.类”名称 //这里要类型转换 c = (Car) Class.forName("net.esrib.Factory.FactoryDemo." + type). newInstance(); } catch (ClassNotFoundException ex) { } catch (IllegalAccessException ex) { } catch (InstantiationException ex) { } return c; } } public class FactoryDemo { public static void main(String [] args){ Car c=Factory.getCarInstance("Benz"); } }