抽象Car类: public abstract class Car{ public abstract void createCar(); } 具体实现类: public class AuDi extends Car{ @Override public void createCar(){ System.out.println("Audi"); } } public class BMW extends Car{ @Override public void createCar(){ System.out.println("BMW"); } } 工厂类: public class FactoryCar{ public static <T extends Car> getCar(class<T> clz){ Car car = null; try{ car = (Car) class.forName(clz.getName()).newInstance(); }catch(Exception e){ e.printStackTrace(); } return (T) car; } } 使用factory: Car audi = FactoryCar.getCar(Audi.class); audi.createCar(); Car bmw = FactoryCar.getCar(Audi.class); bmw.createCar();
抽象car类可以换成接口,具体看:http://www.runoob.com/design-pattern/factory-pattern.html