设计模式-工厂模式

文章目录

一、详解

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

二、代码

  • 源码: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.
相关推荐
qqxhb6 小时前
26|Agent 设计模式:ReAct、Plan-and-Solve 与反射
设计模式·react模式·plan-and-solve·reflection模式
hssfscv7 小时前
软件设计师下午题六——Java的各种设计模式
java·算法·设计模式
zhaoshuzhaoshu9 小时前
设计模式之创建型设计模式详细解析(含示例)
单例模式·设计模式·架构
倚楼盼风雨10 小时前
浅析设计模式-23种设计模式剖析
设计模式
Momentary_SixthSense1 天前
设计模式之工厂模式
java·开发语言·设计模式
Java码农也是农1 天前
Multi-Agent 系统设计模式
设计模式·agent·multi-agent
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
workflower2 天前
深度学习是通用型人工智能的基础
人工智能·深度学习·设计模式·软件工程·软件构建·制造
Meme Buoy2 天前
11.3设计模式-新
设计模式
cmpxr_2 天前
【单片机】常用设计模式
单片机·嵌入式硬件·设计模式