手写Java设计模式之抽象工厂模式,附源码解读

接上篇,抽象工厂模式将汽车的一些属性可以抽象出来,可以理解为给不同汽车品牌生成时加上不同的特性,如颜色等,具体代码如下:

引入颜色接口:

public interface Colour {
    void fill();
}

将颜色与汽车生成品牌抽象出来,增加抽象类:

public abstract class CarAndColourFactory {
    public abstract Car getCar(String CarType);
    public abstract Colour getColour(String colour);
}

继承抽象类,分别对不同属性的特征进行操作,如涂上颜色等,首先实现颜色接口:

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;
    }
}

增加一个根据参数区分增加汽车属性的加工工厂类,如下:

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;
    }
}

进行汽车加工:

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();
    }
}

产生结果:
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tuple_Margin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值