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

发布于:2024-04-20 ⋅ 阅读:(19) ⋅ 点赞:(0)

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一,这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

工厂模式提供了一种创建对象的方式,而无需指定要创建的具体类。

工厂模式属于创建型模式,它在创建对象时提供了一种封装机制,将实际创建对象的代码与使用代码分离。

以汽车生产为例,我们在生产汽车的时候,找到汽车加工厂,我们只需要给对方品牌信息,然后对方就可以生产出不同品牌的汽车,而不需要关注加工过程。

具体代码如下:

首先创建汽车的生产接口:

public interface Car {
     void draw();
}

其次,分别让不同品牌实现汽车生产接口,后续如果需要增加新的品牌,仅需增加实现类即可,代码如下:

public class XiaoMi implements Car {
    @Override
    public void draw() {
        System.out.println("生产小米汽车");
    }
}

public class Tesla implements Car {
    @Override
    public void draw() {
        System.out.println("生产特斯拉");
    }
}

public class HuaWei implements Car {
    @Override
    public void draw() {
        System.out.println("生产问界汽车");
    }
}

增加一个汽车工厂,按照不同品牌生产汽车:

public class CarFactory {
    
    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;
    }
}

最后,实现调用(生产):

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

生成结果:

在这里插入图片描述