设计模式-工厂模式

文章目录

一、详解

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

二、代码

  • 源码: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.
相关推荐
短剑重铸之日5 小时前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
feasibility.5 小时前
AI 编程助手进阶指南:从 Claude Code 到 OpenCode 的工程化经验总结
人工智能·经验分享·设计模式·自动化·agi·skills·opencode
BD_Marathon6 小时前
七大设计原则介绍
设计模式
YigAin8 小时前
Unity23种设计模式之 享元模式
设计模式·享元模式
范纹杉想快点毕业21 小时前
实战级ZYNQ中断状态机FIFO设计
java·开发语言·驱动开发·设计模式·架构·mfc
茂桑1 天前
DDD领域驱动设计-基础设施层
设计模式·架构
小温冲冲1 天前
通俗且全面精讲工厂设计模式
设计模式
进击的小头1 天前
设计模式与C语言高级特性的结合
c语言·设计模式
小温冲冲1 天前
通俗且全面精讲单例设计模式
开发语言·javascript·设计模式
Vivienne_ChenW1 天前
DDD领域模型在项目中的实战
java·开发语言·后端·设计模式