接上篇,抽象工廠模式將汽車的一些屬性可以抽象出來,可以理解為給不同汽車品牌生成時加上不同的特性,如顏色等,具體代碼如下:
引入顏色接口:
public interface Colour {
void fill();
}
將顏色與汽車生成品牌抽象出來,增加抽象類:
public abstract class CarAndColourFactory {
public abstract Car getCar(String CarType);
public abstract Colour getColour(String colour);
}
繼承抽象類,分別對不同屬性的特征進行操作,如涂上顏色等,首先實現(xiàn)顏色接口:
public class Green implements Colour {
@Override
public void fill() {
System.out.println("涂上綠色");
}
}
public class Red implements Colour {
@Override
public void fill() {
System.out.println("涂上紅色");
}
}
汽車品牌和汽車顏色分別繼承抽象類:
public class CarTypeFactory extends CarAndColourFactory{
@Override
public Car getCar(String CarType) {
if(CarType == null){
return null;
}
if(CarType.equalsIgnoreCase("XiaoMi")){
return new XiaoMi();
} else if(CarType.equalsIgnoreCase("HuaWei")){
return new HuaWei();
} else if(CarType.equalsIgnoreCase("Tesla")){
return new Tesla();
}
return null;
}
@Override
public Colour getColour(String colour) {
return null;
}
}
public class ColourFactory extends CarAndColourFactory{
@Override
public Car getCar(String CarType) {
return null;
}
@Override
public Colour getColour(String colour) {
if(colour == null){
return null;
}
if(colour.equalsIgnoreCase("Green")){
return new Green();
} else if(colour.equalsIgnoreCase("Red")){
return new Red();
}
return null;
}
}
增加一個根據(jù)參數(shù)區(qū)分增加汽車屬性的加工工廠類,如下:
public class FactoryProducer {
public static CarAndColourFactory get(String choice){
if(choice.equalsIgnoreCase("Car")){
return new CarTypeFactory();
}else if(choice.equalsIgnoreCase("Colour")){
return new ColourFactory();
}
return null;
}
}
進行汽車加工:文章來源:http://www.zghlxwxcb.cn/news/detail-858116.html
public class CarTest {
public static void main(String[] args){
/* CarFactory carFactory = new CarFactory();
carFactory.getCar("xiaomi").draw();
carFactory.getCar("huawei").draw();
carFactory.getCar("tesla").draw();*/
CarAndColourFactory carAndColourFactory1 = FactoryProducer.get("Car");
carAndColourFactory1.getCar("xiaomi").draw();
CarAndColourFactory carAndColourFactory= FactoryProducer.get("Colour");
carAndColourFactory.getColour("Green").fill();
}
}
產(chǎn)生結果:文章來源地址http://www.zghlxwxcb.cn/news/detail-858116.html
到了這里,關于手寫Java設計模式之抽象工廠模式,附源碼解讀的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!