设计模式-01简单工厂模式详解 详细代码对比

目录

  • ChatGpt问答
    • 原生代码
    • 简单工厂模式代码
  • 简单工厂模式(Simple Factory Pattern)
  • 新增boat 对比两种方法
    • 原生代码
    • 为什么使用强制转换?
    • 简单工厂模式
  • 简单工厂方法总结
    • 与原生代码的区别:
    • 优点:
    • 缺点:
  • 参考

本文将介绍什么事简单工厂模式,为什么要使用这个模式?比起原生代码它是如何降低代码的耦合度的,以及详细的代码对比,结合ChatGPT的问答进行讲解,也是自己学习的记录,有不对的地方请指正。

ChatGpt问答

Q:Give an example to illustrate the benefits of reducing the coupling
of the simple factory model in java, which is best reflected in code

举个例子来说明java中简单工厂模式减少耦合的好处,在代码中最能体现

Certainly! Let’s illustrate the benefits of reducing coupling by using a simple factory model in Java. We’ll start with a coupled implementation and then refactor it to reduce coupling.

当然! 让我们说明一下在 Java 中使用简单工厂模型来减少耦合的好处。 我们将从耦合实现开始,然后重构它以减少耦合。

Coupled Implementation (High Coupling):

Consider a simple factory that produces different types of vehicles (e.g., cars and bicycles) based on a provided type. In this coupled example, the factory method has a high level of coupling with the concrete vehicle classes.

考虑一个简单的工厂,它根据提供的类型生产不同类型的车辆(例如汽车和自行车)。 在这个耦合示例中,工厂方法与具体车辆类具有高度耦合。

原生代码

class VehicleFactory {public Vehicle createVehicle(String type) {if ("car".equalsIgnoreCase(type)) {return new Car();} else if ("bicycle".equalsIgnoreCase(type)) {return new Bicycle();} else {throw new IllegalArgumentException("Invalid vehicle type");}}
}class Car {void start() {System.out.println("Car started.");}
}class Bicycle {void start() {System.out.println("Bicycle started.");}
}public class Main {public static void main(String[] args) {VehicleFactory factory = new VehicleFactory();Vehicle vehicle1 = factory.createVehicle("car");vehicle1.start(); // Output: Car started.Vehicle vehicle2 = factory.createVehicle("bicycle");vehicle2.start(); // Output: Bicycle started.}
}

In this example, the VehicleFactory class has high coupling because it directly creates instances of Car and Bicycle. If we need to add more types of vehicles in the future, we would need to modify the factory method, resulting in increased coupling and reduced flexibility.

在这个例子中,VehicleFactory类具有高耦合性,因为它直接创建CarBicycle的实例。 如果以后需要增加更多类型的车辆,就需要修改工厂方法,导致耦合性增加,灵活性降低。

简单工厂模式代码

Reduced Coupling Implementation (Low Coupling):

To reduce coupling, we can use interfaces and abstract classes to define a common contract for all vehicles. This way, the factory method doesn’t need to know the concrete classes of vehicles.

interface Vehicle {void start();
}class Car implements Vehicle {public void start() {System.out.println("Car started.");}
}class Bicycle implements Vehicle {public void start() {System.out.println("Bicycle started.");}
}class VehicleFactory {public Vehicle createVehicle(String type) {if ("car".equalsIgnoreCase(type)) {return new Car();} else if ("bicycle".equalsIgnoreCase(type)) {return new Bicycle();} else {throw new IllegalArgumentException("Invalid vehicle type");}}
}public class Main {public static void main(String[] args) {VehicleFactory factory = new VehicleFactory();Vehicle vehicle1 = factory.createVehicle("car");vehicle1.start(); // Output: Car started.Vehicle vehicle2 = factory.createVehicle("bicycle");vehicle2.start(); // Output: Bicycle started.}
}

In this refactored example, we’ve introduced an interface Vehicle, which both Car and Bicycle implement. The VehicleFactory now returns instances of the Vehicle interface instead of concrete classes. This reduces coupling because the factory method doesn’t depend on specific implementations, making it easier to extend the system with new types of vehicles without modifying existing code.

在这个重构的示例中,我们引入了一个“Vehicle”接口,“Car”和“Bicycle”都实现了该接口。 “VehicleFactory”现在返回“Vehicle”接口的实例,而不是具体类。 这减少了耦合,因为工厂方法不依赖于特定的实现,从而可以更轻松地使用新型车辆扩展系统,而无需修改现有代码。

简单工厂模式(Simple Factory Pattern)

是一种创建型设计模式,它提供了一种简单的方法来创建对象,而不需要直接暴露对象的创建逻辑给客户端。

简单工厂模式又称静态工厂方法模式。它存在的目的很简单:定义一个用于创建对象的接口。
组成结构:

  1. 工厂类角色(Creator):这是本模式的核心,含有一定的商业逻辑和判断逻辑。在java中它往往由一个具体类实现。

  2. 抽象产品角色(Product):它一般是具体产品继承的父类或者实现的接口。在java中由接口或者抽象类来实现。

  3. 具体产品角色(ConcreteProduct):工厂类所创建的对象就是此角色的实例。在java中由一个具体类实现。

用类图表示它们之间的关系
在这里插入图片描述
抽象产品角色–Vehicle 交通工具
具体产品角色 – Car、Bicycle
工厂类角色–VehicleFactory

新增boat 对比两种方法

原生代码

Certainly! In a high coupling approach, you would directly create instances of vehicle classes within the factory method, which can lead to tight dependencies between the factory and the concrete vehicle classes. Here’s an example of a high coupling approach:

当然! 在高耦合方法中,您将直接在工厂方法中创建车辆类的实例,这可能导致工厂和具体车辆类之间的紧密依赖关系。 这是一个高耦合方法的示例:

class Car {void start() {System.out.println("Car started.");}
}class Bicycle {void start() {System.out.println("Bicycle started.");}
}class Boat {void start() {System.out.println("Boat started.");}
}class VehicleFactory {public Object createVehicle(String type) {if ("car".equalsIgnoreCase(type)) {return new Car();} else if ("bicycle".equalsIgnoreCase(type)) {return new Bicycle();} else if ("boat".equalsIgnoreCase(type)) {return new Boat();} else {throw new IllegalArgumentException("Invalid vehicle type");}}
}public class Main {public static void main(String[] args) {VehicleFactory factory = new VehicleFactory();Car car = (Car) factory.createVehicle("car");car.start(); // Output: Car started.Bicycle bicycle = (Bicycle) factory.createVehicle("bicycle");bicycle.start(); // Output: Bicycle started.Boat boat = (Boat) factory.createVehicle("boat");boat.start(); // Output: Boat started.}
}

In this high coupling approach:

  1. Each vehicle class (Car, Bicycle, Boat) is directly instantiated within the createVehicle method of the VehicleFactory.
  2. To use a specific vehicle, you need to cast the object returned by the factory to the corresponding vehicle class (Car, Bicycle, Boat).
  3. Adding a new type of vehicle would require modifying the VehicleFactory to create that vehicle type directly.

在这种高耦合方法中:

  1. 每个车辆类(“Car”、“Bicycle”、“Boat”)都直接在“VehicleFactory”的“createVehicle”方法中实例化。
  2. 要使用特定的车辆,需要将工厂返回的对象转换为相应的车辆类(CarBicycleBoat)。
  3. 添加新类型的车辆需要修改 VehicleFactory 以直接创建该车辆类型。

High coupling can make the code less flexible and harder to maintain because any changes to the factory method or the concrete vehicle classes may affect other parts of the code that rely on them. It’s generally a best practice to reduce coupling and use interfaces or abstract classes to achieve better flexibility and maintainability.

高耦合会使代码不太灵活且难以维护,因为对工厂方法或具体车辆类的任何更改都可能会影响依赖它们的代码的其他部分。 通常,最佳实践是减少耦合并使用接口或抽象类来实现更好的灵活性和可维护性。

为什么使用强制转换?

Car car = (Car) factory.createVehicle(“car”)

In the high coupling approach I provided earlier, you are correct that type casting is required when you retrieve the created objects from the factory. This is a limitation of high coupling because you’re directly creating instances of specific classes within the factory method. Let me explain this in more detail:

In the createVehicle method of the VehicleFactory, the factory creates instances of Car, Bicycle, or Boat based on the type parameter.

Since the createVehicle method is declared to return an Object, when you retrieve the created object, it’s treated as an Object reference.

To use the specific functionality of a Car, for example, you need to cast the Object reference back to Car to access Car-specific methods like start.

This type casting introduces potential issues because if you provide the wrong type for the type parameter or if you introduce a new vehicle type in the future, you might get runtime errors (ClassCastException) if the casting doesn’t match the actual type.

In contrast, a low coupling approach, as demonstrated in the previous example, uses interfaces or abstract classes to create a common contract for all vehicles. This way, you can avoid type casting and handle all vehicles uniformly by relying on the common interface. It provides better flexibility, maintainability, and type safety, as you don’t need to cast objects to specific types when using them.

在我之前提供的高耦合方法中,当您从工厂检索创建的对象时,需要进行类型转换,这是正确的。 这是高耦合的限制,因为您是在工厂方法中直接创建特定类的实例。 让我更详细地解释一下:

在 VehicleFactory 的 createVehicle 方法中,工厂根据类型参数创建 Car、Bicycle 或 Boat 的实例。

由于 createVehicle 方法被声明为返回一个对象,因此当您检索创建的对象时,它将被视为对象引用。

例如,要使用汽车的特定功能,您需要将对象引用强制转换回汽车以访问汽车特定的方法,例如启动。

这种类型转换会带来潜在的问题,因为如果您为类型参数提供了错误的类型,或者如果您将来引入新的车辆类型,并且转换与实际类型不匹配,则可能会出现运行时错误 (ClassCastException)。

相反,低耦合方法(如前面的示例所示)使用接口或抽象类为所有车辆创建通用契约。 这样,您可以避免类型转换并依靠通用接口统一处理所有车辆。 它提供了更好的灵活性、可维护性和类型安全性,因为您在使用对象时不需要将对象强制转换为特定类型。

简单工厂模式

Q:show me High Coupling method

Certainly! Let’s add a new Boat vehicle to the existing code. We’ll follow the same approach of using an interface for Boat and updating the factory method to create Boat instances without modifying the existing code.

当然! 让我们在现有代码中添加一个新的“Boat”车辆。 我们将遵循相同的方法,使用“Boat”接口并更新工厂方法来创建“Boat”实例,而无需修改现有代码。

Adding a Boat Vehicle (Low Coupling):

interface Vehicle {void start();
}class Car implements Vehicle {public void start() {System.out.println("Car started.");}
}class Bicycle implements Vehicle {public void start() {System.out.println("Bicycle started.");}
}class Boat implements Vehicle {public void start() {System.out.println("Boat started.");}
}class VehicleFactory {public Vehicle createVehicle(String type) {if ("car".equalsIgnoreCase(type)) {return new Car();} else if ("bicycle".equalsIgnoreCase(type)) {return new Bicycle();} else if ("boat".equalsIgnoreCase(type)) {return new Boat();} else {throw new IllegalArgumentException("Invalid vehicle type");}}
}public class Main {public static void main(String[] args) {VehicleFactory factory = new VehicleFactory();Vehicle vehicle1 = factory.createVehicle("car");vehicle1.start(); // Output: Car started.Vehicle vehicle2 = factory.createVehicle("bicycle");vehicle2.start(); // Output: Bicycle started.Vehicle vehicle3 = factory.createVehicle("boat");vehicle3.start(); // Output: Boat started.}
}

In this updated code, we’ve introduced a new Boat class that implements the Vehicle interface. The VehicleFactory has been updated to handle the creation of Boat instances when “boat” is passed as the type. This allows us to add a new type of vehicle (in this case, a boat) without modifying the existing code for the factory or the other vehicles. This demonstrates the flexibility and low coupling achieved by using interfaces and an abstract factory approach.

在此更新的代码中,我们引入了一个新的“Boat”类,它实现了“Vehicle”接口。 “VehicleFactory”已更新,可以在“boat”作为类型传递时处理“Boat”实例的创建。 这使我们能够添加一种新型车辆(在本例中为船),而无需修改工厂或其他车辆的现有代码。 这展示了通过使用接口和抽象工厂方法实现的灵活性和低耦合。

简单工厂方法总结

与原生代码的区别:

从三个维度来说明:
抽象产品角色–Vehicle 交通工具
具体产品角色 – Car、Bicycle
工厂类角色–VehicleFactory

1 简单工厂模式中抽象产品角色Vehicle 使用interface,原生代码是class
2 简单工厂模式中具体产品角色Car,需要实现接口,原生代码为单独类
3 简单工厂模式中具体工厂类角色–VehicleFactory 返回对象是Vehicle 接口,原生代码的返回对象是Object

优点:

  • 将对象的创建逻辑集中在工厂类中,降低了客户端的复杂度。
  • 隐藏了创建对象的细节,客户端只需要关心需要创建何种对象,无需关心对象是如何创建的。
    可以通过修改工厂类来轻松添加新的产品类

缺点:

  • 如果产品的类太多,会导致工厂类中的代码变得很复杂,难以维护。
  • 添加新产品时,需要修改工厂类,也就是会在OperationFactory类中新增case语句,这违背了开闭原则。

总体而言,简单工厂模式适用于创建对象的逻辑相对简单,且产品类的数量较少的场景。对于更复杂的对象创建和对象之间的依赖关系,可以考虑使用其他创建型设计模式,如工厂方法模式或抽象工厂模式。

参考

1 设计模式-01.简单工厂方法https://juejin.cn/post/7267091509953855543

2 JAVA设计模式(三) – 工厂模式
https://juejin.cn/post/7257441765976162361?searchId=202309061335355A323BC0D43AD67B950D#heading-0

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/70400.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

二维数组笔试题及其解析

Lei宝啊 :个人主页 愿所有美好不期而遇 前言: 数组名在寻常情况下表示首元素地址,但有两种情况例外: 1.sizeof(数组名),这里的数组名表示整个数组,计算的是整个数组的大小 2.&数组名,这里的…

Hystrix和Sentinel熔断降级设计理念

目录 1 基本介绍2 Hystrix信号量和线程池区别2.1 信号量模式2.2 线程池模式2.3 注意 3 Sentinel介绍 1 基本介绍 Sentinel 和 Hystrix 的原则是一致的: 当检测到调用链路中某个资源出现不稳定的表现,例如请求响应时间长或异常比例升高的时候,则对这个资源…

目前无法建立VS2013与Qt的连接???

因为下载组件的时候,没有哪个选项,还是没有MSVC2013

微信小程序集成腾讯im,会话列表数据过多(长列表),卡顿问题的解决

说明 我这边用小程序集成im,然后结合公司的需求,做了一个聊天的小程序,在测试上线的时候没有问题,结果到客户那边,因为他们聊天的人多,会话列表达到了300多条,然后点击会话列表,进入…

C#,《小白学程序》第十六课:随机数(Random)第三,正态分布的随机数的计算方法与代码

1 文本格式 // 定义一个全局性&#xff08;公共&#xff09;的随机数发生器&#xff0c;便于大家&#xff08;各函数&#xff09;后面共同使用。 Random global_rnd new Random(); /// <summary> /// 生成服从标准正态分布的随机数 /// https://zhuanlan.zhihu.com/p/6…

Postern配置HTTP和HTTPS的步骤

Postern是一款强大的Android代理工具&#xff0c;它允许您在设备上配置全局代理来实现安全、隐私保护和自由上网。本文将详细介绍如何使用Postern在Android设备上配置HTTP和HTTPS代理&#xff0c;为您提供更便捷的上网体验。 步骤1&#xff1a;下载和安装Postern应用 首先&am…

pdf怎么合并在一起?几种方法快速合并

pdf怎么合并在一起&#xff1f;在处理PDF文件时&#xff0c;有时需要将多个PDF文件合并成一个文件。这种操作在日常学习、工作和生活中很常见。但是&#xff0c;如果没有专业的PDF工具&#xff0c;这项任务可能会变得非常繁琐、耗时和费力。因此&#xff0c;我们需要一款功能强…

Faster RCNN

【简介】 Faster RCNN[7]是第一个端到端&#xff0c;最接近于实时性能的深度学习检测算法&#xff0c;该网络的主要创新点就是提出了区域选择网络用于申城候选框&#xff0c;能几大提升检测框的生成速度。该网络首先输入图像到卷积网络中&#xff0c;生成该图像的特征映射。在特…

ActiveReportsJs 账票印刷

参考资料 官方文档 一. HTML部分 在页面上添加了Loading效果&#xff0c;账票印刷开始时显示Loading效果&#xff0c;印刷结束后隐藏Loading效果。ar-js-core.js是核心文件ar-js-pdf.js用来印刷PDFar-js-xlsx.js用来印刷EXCELar-js-locales.js用来设置语言 <!DOCTYPE htm…

优化SOCKS5的方法

在今天的互联网世界中&#xff0c;保护个人隐私和提升网络速度至关重要。作为一种常用的代理协议&#xff0c;SOCKS5代理服务器不仅可以保护您的隐私&#xff0c;还可以实现更快速的网络访问。本文将为您介绍一些优化SOCKS5代理服务器的方法&#xff0c;以提高网络速度和安全性…

阿里云2核4G服务器5M带宽五年租用价格表

阿里云2核4G服务器5M带宽可以选择轻量应用服务器或云服务器ECS&#xff0c;轻量2核4G4M带宽服务器297元一年&#xff0c;2核4G云服务器ECS可以选择计算型c7、c6或通用算力型u1实例等&#xff0c;买5年可以享受3折优惠&#xff0c;阿腾云分享阿里云服务器2核4G5M带宽五年费用表&…

Xcode,swift:Error Domain=kCLErrorDomain Code=1 (null)问题解决

问题描述: iOS开发时,当使用用户的位置权限时,获取用户经纬度报错:Error DomainkCLErrorDomain Code1 "(null)",错误域kCLError域代码1“(null)” 解决方法: 打开模拟机的设置-通用-语言与地区 将地区设置为中国(如果你的开发位置在中国的话) 点击左上方Features,选择…

发光太阳聚光器的蒙特卡洛光线追踪研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

【大数据】Flink 详解(七):源码篇 Ⅱ

本系列包含&#xff1a; 【大数据】Flink 详解&#xff08;一&#xff09;&#xff1a;基础篇【大数据】Flink 详解&#xff08;二&#xff09;&#xff1a;核心篇 Ⅰ【大数据】Flink 详解&#xff08;三&#xff09;&#xff1a;核心篇 Ⅱ【大数据】Flink 详解&#xff08;四…

完成Centos上使用SSH公钥进行免密上传文件到gitee的步骤后,测试免密推送到gitee的时候还是需要输入邮箱和密码

如果你已经按照正确的步骤设置了SSH公钥并进行了免密测试&#xff0c;但仍然需要输入邮箱地址和密码才能推送到gitee&#xff0c;那么可能有以下几种原因&#xff1a; 您可能没有使用SSH URL来推送代码。请确保您使用的是SSH URL而不是HTTPS URL来推送代码。您可以使用命令 gi…

Opencv快速入门教程,Python计算机视觉基础

快速入门 OpenCV 是 Intel 开源计算机视觉库。它由一系列 C 函数和少量 C 类构成&#xff0c; 实现了图像处理和计算机视觉方面的很多通用算法。 OpenCV 拥有包括 300 多个 C 函数的跨平台的中、高层 API。它不依赖于其它的外部库——尽管也 可以使用某些外部库。 OpenCV 对非…

弹窗、抽屉、页面跳转区别 | web交互入门

当用户点击或触发浏览页面的某个操作&#xff0c;有很多web交互方式&#xff0c;可以大致分为弹窗、抽屉、跳转新页面三种web交互方式。虽然这三种web交互方式看起来没什么不同&#xff0c;但实际上弹窗、抽屉、跳转新页面对交互体验有蛮大的影响。 这需要UI\UX设计师针对不同…

Liquid Studio 2023.2 Crack

Liquid Studio 提供了用于XML和JSON开发 的高级工具包以及Web 服务测试、数据映射和数据转换工具。 开发环境包含一整套用于设计 XML 和 JSON 数据结构和模式的工具。这些工具提供编辑、验证和高级转换功能。对于新手或专家来说&#xff0c;直观的界面和全面的功能将帮助您节省…

Nginx全家桶配置详解

源码包安装NGINX A&#xff0c;搭建Web Server&#xff0c;任意HTML页面&#xff0c;其8080端口提供Web访问服务&#xff0c;截图成功访问http(s)&#xff1a;//[Server1]:8080并且回显Web页面。保留Server1&#xff0c;但是不允许直接访问Server 1&#xff0c;再部署1套NGINX …

安卓10创建文件夹失败

最近在做拍照录像功能&#xff0c;已经有了文件读写权限&#xff0c;却发现在9.0手机上正常使用&#xff0c;但是在安卓12系统上根本没有创建文件夹。经过研究发现&#xff0c;创建名称为“DCIM”的文件夹可以&#xff0c;别的又都不行。而且是getExternalStorageDirectory和ge…