java设计模式:工厂模式

1:在平常的开发工作中,我们可能会用到不同的设计模式,合理的使用设计模式,可以提高开发效率,提高代码质量,提高系统的可拓展性,今天来简单聊聊工厂模式。

2:工厂模式是一种创建对象的设计模式,平常我们创建对象可能使用new来创建,使用工厂模式,我们可以通过调用工厂类的静态方法或者实例方法来创建对象。

抽象产品:主要是父类或者接口,定义了需要实现的方法

具体产品:实现类,实现父类或者接口的方法

工厂类:负责创建对象

3:简单示例:

抽象产品:定义一个动物接口,里面包含eat()方法:

java 复制代码
package test.boot.factory;

public interface Animal {

    void eat();

}

具体产品:定义两个类:Tiger和Sheep分别实现eat()方法

java 复制代码
package test.boot.factory;

public class Sheep implements Animal{
    @Override
    public void eat() {
        System.out.println("吃草");
    }
}
java 复制代码
package test.boot.factory;

public class Tiger implements Animal{
    @Override
    public void eat() {
        System.out.println("吃肉");
    }
}

工厂类:

sql 复制代码
package test.boot.factory;

public class AnimalFactory {

    public static Animal create(String type) {
        if (type.equals("tiger")) {
            return new Tiger();
        } else if (type.equals("sheep")) {
            return new Sheep();
        }
        throw new IllegalArgumentException("Invalid Animal type: " + type);
    }

}

4:客户端:调用实现

java 复制代码
package test.boot.factory;

public class Test {

    public static void main(String[] args) {
        Animal animal1 = AnimalFactory.create("tiger");
        animal1.eat();

        Animal animal2 = AnimalFactory.create("sheep");
        animal2.eat();
    }

}

运行结果:

5:以上为工厂模式的简单示例。合理的使用,可以提高代码的可维护性和拓展性,隐藏了实现的具体细节,客户端只需要调用即可。

相关推荐
xieliyu.4 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
明夜之约5 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee5 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Jinkxs5 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
辣机小司5 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
fangdengfu1236 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
云烟成雨TD6 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
星越华夏6 小时前
ESP32-CAM图像传输项目说明文档
java·后端·struts·esp32
Jinkxs7 小时前
Java 跨域14-Java 与区块链(Hyperledger)集成
java·开发语言·区块链
晨曦中的暮雨8 小时前
Golang速通(Javaer版)
java·开发语言·后端·golang