设计模式-工厂模式

文章目录

一、详解

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

二、代码

  • 源码: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.
相关推荐
geovindu21 小时前
python: Generators Pattern
开发语言·python·设计模式·生成器模式
雨浓YN1 天前
基于设计模式的Winform软件框架-01Xml\Log\Ini日志(单例模式+生产者消费者模式)
单例模式·设计模式
艾利克斯冰1 天前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
星心源七境2 天前
七境体系全解析:从六韬兵法到AI锁颜,一套贯穿古典智慧与现代应用的成长操作系统
人工智能·设计模式·设计
qq_297574672 天前
设计模式系列文章(基础篇第21篇):迭代器模式——遍历聚合解耦,实现统一迭代访问
设计模式·迭代器模式
禅思院2 天前
前端请求取消与调度完全指南:从 AbortController 到企业级优先级架构
前端·设计模式·前端框架
小bo波2 天前
用匿名内部类优雅地计算方法执行时间
java·设计模式·性能测试·模板方法模式·lambda·代码优化·匿名内部类
写代码的小阿帆2 天前
行为型设计模式之观察者(发布-订阅)模式
设计模式
王_teacher2 天前
23种设计模式全解析(GoF 设计模式)
设计模式·软考·软件设计师·软考中级
阿坤带你走近大数据2 天前
分别介绍下java主流的开发框架、设计模式与对应编程语言的高级特性
java·开发语言·设计模式