public static Car getCar(String name) { if ("BMW".equals(name)) { return new BMWCar(); } if ("BAOJUN".equals(name)) { return new BaojunCar(); } throw new RuntimeException("unsupport car name "); }
}
1 2 3 4
public interface Car { void desc(); }
1 2 3 4 5 6
public class BMWCar implements Car { @Override public void desc() { System.out.println("我是宝马~"); } }
1 2 3 4 5 6
public class BaojunCar implements Car { @Override public void desc() { System.out.println("我是宝骏!"); } }
产品类(宝马、宝骏)都继承Car类
工厂类根据入参不同返回不通的产品 下面是主方法
1 2 3 4 5 6 7 8 9 10
public class Main { public static void main(String[] args) { Car bmw = CarFactory.getCar("BMW"); bmw.desc(); Car baojun = CarFactory.getCar("BAOJUN"); baojun.desc(); Car xxx = CarFactory.getCar("xxx"); xxx.desc(); } }