定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
代码实现
public interface Car { public void run(); }
public class Audi implements Car { public void run() { System.out.println("奥迪在跑!"); } }
public class Byd implements Car { @Override public void run() { System.out.println("比亚迪再跑"); } }
public interface CarFactory { Car createCar(); }
public class AudiFactory implements CarFactory{ public Car createCar() { return new Audi(); } }
public class BydFactory implements CarFactory{ public Car createCar() { return new Byd(); } }
public class FactoryMethodTest { @Test public void test(){ Car audi = new AudiFactory().createCar(); audi.run(); System.out.println("-----------"); Car byd = new BydFactory().createCar(); byd.run(); } }