产品接口:
public interface Car {
}
产品一:
public class BMWSUV implements Car {
public BMWSUV() {
System.out.println("create BMW SUV.");
}
}
产品二:
public class BMWSportsCar implements Car {
public BMWSportsCar() {
System.out.println("Create BMW Sports Car.");
}
}
产品三:
public class TeslaSUV implements Car {
public TeslaSUV() {
System.out.println("create Tesla SUV.");
}
}
产品四:
public class TeslaSportsCar implements Car {
public TeslaSportsCar() {
System.out.println("create Tesla Sports Car.");
}
}
产品工厂接口:
public interface ICarsFactory {
public Car suvCreate();
public Car sportsCarCreate();
}
产品族一工厂:
public class BMWCarsFactory implements ICarsFactory {
//生产1,2号产品
@Override
public Car suvCreate() {
return new BMWSUV();
}
@Override
public Car sportsCarCreate() {
return new BMWSportsCar();
}
}
产品族二工厂:
public class TeslaCarsFactory implements ICarsFactory {
//生产3,4号产品
@Override
public Car suvCreate() {
return new TeslaSUV();
}
@Override
public Car sportsCarCreate() {
return new TeslaSportsCar();
}
}
调用者:
public class Consumer {
public static void main(String[] args) {
ICarsFactory bmwFactory = new BMWCarsFactory();
ICarsFactory teslaFactory = new TeslaCarsFactory();
Car bmwSuv = bmwFactory.suvCreate();
Car bmwSports = bmwFactory.sportsCarCreate();
Car teslaSuv = teslaFactory.suvCreate();
Car teslaSports = teslaFactory.sportsCarCreate();
}
}