设计模式-工厂模式

文章目录

一、详解

  • 概念:定义一个产品接口 ,根据向工厂类 传递的类型 ,创建相应的产品实例并返回
  • 主要用途:根据不同条件,创建不同产品
  • 代码:产品接口、产品子类、工厂类

二、代码

  • 源码:https://gitee.com/deschen/designPattern-study

  • 以交通工具为例,根据不同类型,驾驶不同交通工具

  • 产品接口

    java 复制代码
    public interface Transport {
    
        void drive();
    }
  • 产品子类

    java 复制代码
    public class Bicycle implements Transport {
    
        @Override
        public void drive() {
            System.out.println("Driving a bicycle.");
        }
    }
    
    public class Car implements Transport {
    
        @Override
        public void drive() {
            System.out.println("Driving a car.");
        }
    }
    
    public class Plane implements Transport {
    
        @Override
        public void drive() {
            System.out.println("Driving a plane.");
        }
    }
  • 工厂类

    java 复制代码
    package cn.deschen.designPattern.factoryPattern.factory;
    
    import cn.deschen.designPattern.factoryPattern.entity.Bicycle;
    import cn.deschen.designPattern.factoryPattern.entity.Car;
    import cn.deschen.designPattern.factoryPattern.entity.Plane;
    import cn.deschen.designPattern.factoryPattern.entity.Transport;
    
    /**
     * @Author hanbin_chen
     * @Description 交通工具工厂,根据条件动态创建对象并返回
     * @Version V1.0.0
     */
    public class TransportFactory {
    
        public static Transport createTransport(String type) {
            switch (type) {
                case "car":
                    return new Car();
                case "bicycle":
                    return new Bicycle();
                case "plane":
                    return new Plane();
                default:
                    throw new IllegalArgumentException("Invalid transport type: " + type);
            }
        }
    }
  • 用例

    java 复制代码
    public class Demo {
    
        public static void main(String[] args) {
            // 创建汽车
            Transport car = TransportFactory.createTransport("car");
            car.drive();
    
            // 创建自行车
            Transport bicycle = TransportFactory.createTransport("bicycle");
            bicycle.drive();
    
            // 创建飞机
            Transport plane = TransportFactory.createTransport("plane");
            plane.drive();
        }
    }
    
    // 输出
    Driving a car.
    Driving a bicycle.
    Driving a plane.
相关推荐
__万波__6 小时前
二十三种设计模式(十三)--模板方法模式
java·设计模式·模板方法模式
⑩-9 小时前
Java设计模式-命令模式
java·设计模式·命令模式
AM越.9 小时前
Java设计模式超详解--状态设计模式
java·开发语言·设计模式
FreeCode9 小时前
智能体设计模式解析:ReAct模式
设计模式·langchain·agent
程序员爱钓鱼10 小时前
BlackHole 2ch:macOS无杂音录屏与系统音频采集完整技术指南
前端·后端·设计模式
syt_101310 小时前
设计模式之-观察者模式
观察者模式·设计模式
廋到被风吹走1 天前
【Java】常用设计模式及应用场景详解
java·开发语言·设计模式
Jaycee青橙1 天前
软件设计模式详解
设计模式
alibli1 天前
一文学会设计模式之结构型模式及最佳实现
c++·设计模式
电子科技圈1 天前
SiFive车规级RISC-V IP获IAR最新版嵌入式开发工具全面支持,加速汽车电子创新
嵌入式硬件·tcp/ip·设计模式·汽车·代码规范·risc-v·代码复审