Java 代码:用工厂模式创建向日葵、坚果墙和豌豆射手
It looks like you have a Java code snippet that defines a factory pattern for creating different types of plants. However, there are a few issues and missing parts in the code. I'll help you correct and complete it. Here's the corrected and completed version: ```java class Plant { public void show() { System.out.println("这是一个植物"); } } class Sunflower extends Plant { @Override public void show() { System.out.println("向日葵"); } } class Nut extends Plant { @Override public void show() { System.out.println("坚果墙"); } } class Pea extends Plant { @Override public void show() { System.out.println("豌豆射手"); } } class PlantFactory { public static Plant create(String s) { if ("向日葵".equalsIgnoreCase(s)) { return new Sunflower(); } else if ("坚果墙".equalsIgnoreCase(s)) { return new Nut(); } else if ("豌豆射手".equalsIgnoreCase(s)) { return new Pea(); } else { return new Plant(); } } } public class Main { public static void main(String[] args) { Plant sunflower = PlantFactory.create("向日葵"); Plant nut = PlantFactory.create("坚果墙"); Plant pea = PlantFactory.create("豌豆射手"); sunflower.show(); nut.show(); pea.show(); } } ``` Explanation: 1. Plant Class: This is the base class with a default `show` method. 2. Sunflower, Nut, Pea Classes: These are subclasses of `Plant` and override the `show` method to display their specific names. 3. PlantFactory Class: This class contains a static method `create` that takes a string parameter and returns an instance of the corresponding plant class. 4. Main Class: This class contains the `main` method to demonstrate the usage of the factory pattern. Key Points: - Inheritance: Each plant subclass inherits from the `Plant` class. - Polymorphism: The `show` method is overridden in each subclass to provide specific behavior. - Factory Method: The `create` method in `PlantFactory` uses conditional logic to return the appropriate plant object based on the input string. This should work correctly and print the names of the plants when run. ######[AI写代码神器 | 498点数解答 | 2024-10-17 17:03:51]
- Java 实现复制粘贴功能:打造简易文本复制粘贴程序(GPT | 1497点数解答 | 2024-08-25 09:40:33)408
- Java代码:植物工厂创建向日葵、坚果墙与豌豆射手(字节豆包 | 31点数解答 | 2024-10-17 17:03:18)279
- Java 代码:用工厂模式创建向日葵、坚果墙和豌豆射手(阿里通义 | 498点数解答 | 2024-10-17 17:03:51)330
- Java 代码:植物工厂实现向日葵、坚果墙和豌豆射手创建(讯飞星火 | 48点数解答 | 2024-10-17 17:04:18)245
- 解决数据库“dm.jdbc.driver.dmexception: 数据溢出”问题的全步骤指南(阿里通义 | 598点数解答 | 2024-10-15 15:48:38)310
- 达梦数据库数据溢出问题排查及多维度解决方法(阿里通义 | 403点数解答 | 2024-10-15 15:48:41)1147
- Java 创建 HTTP POST 请求实现文件上传:代码示例与注意要点 (字节豆包 | 300点数解答 | 2024-12-06 16:07:20)340
- "Java Code: Uncovering Stock Statistics through CSV File Reading"(字节豆包 | 66点数解答 | 2024-11-13 15:31:04)323
- Java 实现功能丰富的资源管理器:含代码示例与注意要点,数据结构大作业来袭! (字节豆包 | 499点数解答 | 2024-12-31 16:31:32)182
- JavaScript开发难题破解:模拟“原生”方法及Node.js中的相关应用(阿里通义 | 192点数解答 | 2023-11-09 01:16:49)311
- Spring框架实战:从配置到实现,搞定员工信息查询功能(GPT | 2135点数解答 | 2024-06-12 08:32:35)315
- C++实现顺序存储结构基本操作:初始化、插入、删除等全解析(GPT | 1743点数解答 | 2024-09-26 00:20:17)284