public interface CarFactory { ClassACar createClassACar(); ClassBCar createClassBCar(); } public interface ClassACar { String getCarModel(); } public class BenzClassACar implements ClassACar { @Override public String getCarModel() { return "奔驰A级车"; } } public class BmwClassACar implements ClassACar { @Override public String getCarModel() { return "宝马A级车"; } }
public interface ClassBCar { String getCarModel(); } public class BenzClassBCar implements ClassBCar{ @Override public String getCarModel() { return "奔驰B级车"; } } public class BmwClassBCar implements ClassBCar { @Override public String getCarModel() { return "宝马B级车"; } } public class BenzCarFactory implements CarFactory { @Override public BenzClassACar createClassACar() { returnnew BenzClassACar(); }
@Override public BenzClassBCar createClassBCar() { returnnew BenzClassBCar(); } } public class BmwCarFactory implements CarFactory { @Override public BmwClassACar createClassACar() { returnnew BmwClassACar(); } @Override public BmwClassBCar createClassBCar() { returnnew BmwClassBCar(); } } public class AbstractFactoryDemo { public static void main(String[] args) { BenzCarFactory benzCarFactory =new BenzCarFactory(); BenzClassACar benzClassACar = benzCarFactory.createClassACar(); System.out.println(benzClassACar.getCarModel()); BenzClassBCar benzClassBCar = benzCarFactory.createClassBCar(); System.out.println(benzClassBCar.getCarModel()); BmwCarFactory bmwCarFactory =new BmwCarFactory(); BmwClassACar bmwClassACar = bmwCarFactory.createClassACar(); System.out.println(bmwClassACar.getCarModel()); BmwClassBCar bmwClassBCar = bmwCarFactory.createClassBCar(); System.out.println(bmwClassBCar.getCarModel()); } }