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

相关推荐
SimonKing8 分钟前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员
间彧1 小时前
Spring Boot集成Spring Security 6.x完整指南
java
xiezhr2 小时前
用户只需要知道「怎么办」,不需要知道「为什么炸了」
java·api·接口设计规范
xiezhr2 小时前
接口设计18条军规:写给那些半夜被“502”叫醒的人
java·api·restful
RainbowSea11 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea11 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑15 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613515 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊16 小时前
Java学习第22天 - 云原生与容器化
java
渣哥18 小时前
原来 Java 里线程安全集合有这么多种
java