定义:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
举例说明:
car接口:
package factory; public interface Car { String getCarName(); }
car实例1:
package factory; public class AudiCar implements Car { @Override public String getCarName() { return "audi"; } }
car实例2:
package factory; public class BmwCar implements Car { @Override public String getCarName() { return "bmw"; } }
CarFactory抽象类:
package factory; public abstract class CarFactory { Car car; public void saleCar() { car = createCar(); System.out.println("create car"); sale(car); } abstract Car createCar(); void sale(Car car) { System.out.println("sale " + car.getCarName()); } }
具体工厂1:
package factory; public class AudiFactory extends CarFactory { @Override Car createCar() { return new AudiCar(); } }
具体工厂2:
package factory; public class BmwFacory extends CarFactory { @Override Car createCar() { return new BmwCar(); } }
测试类:
package factory; public class Test { public static void main(String[] args) { CarFactory carFactory = new BmwFacory(); carFactory.saleCar(); System.out.println("**********"); carFactory = new AudiFactory(); carFactory.saleCar(); } }
执行结果:
create car
sale bmw
**********
create car
sale audi