提供了比工厂模式更高一级的接口级,用于返回若个工厂之一。这个模式是属于创建模式之一。有几点值得注意:
public enum CarType { SMALL, SEDAN, LUXURY }
public abstract class Car { private CarType model = null; public Car(CarType model) { this.model = model; arrangeParts(); } private void arrangeParts() { // Do one time processing here } // Do subclass level processing in this method protected abstract void construct(); public CarType getModel() { return model; } public void setModel(CarType model) { this.model = model; } }
public class SmallCar extends Car{ SmallCar() { super(CarType.SMALL); construct(); } @Override protected void construct() { System.out.println("Building small car"); // add accessories } }
public class SedanCar extends Car { SedanCar() { super(CarType.SEDAN); construct(); } @Override protected void construct() { System.out.println("Building sedan car"); // add accessories } }
public class LuxuryCar extends Car { LuxuryCar() { super(CarType.LUXURY); construct(); } @Override protected void construct() { System.out.println("Building luxury car"); // add accessories } }定义FactoryCar工厂类,现实具体的调用。
public class CarFactory { public static Car buildCar(CarType model) { Car car = null; switch (model) { case SMALL: car = new SmallCar(); break; case SEDAN: car = new SedanCar(); break; case LUXURY: car = new LuxuryCar(); break; default: // throw some exception break; } return car; } }
public class CarFactoryTest { @SuppressWarnings("deprecation") @Test public void testCarFactory() { Assert.assertEquals(true, CarFactory.buildCar(CarType.SMALL) instanceof Car) ; Assert.assertEquals(true, CarFactory.buildCar(CarType.SEDAN) instanceof Car) ; Assert.assertEquals(true, CarFactory.buildCar(CarType.LUXURY) instanceof Car) ; } }
Building small car Building sedan car Building luxury car