java设计模式:工厂模式

本文介绍了工厂模式的概念,如何通过工厂类动态创建抽象产品(如Animal接口的Tiger和Sheep实现),以及其在提高代码可维护性和扩展性方面的优势。通过实例展示了如何在实际开发中应用工厂模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

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

        工厂类:负责创建对象

        3:简单示例:

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

package test.boot.factory;

public interface Animal {

    void eat();

}

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

package test.boot.factory;

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

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

         工厂类:

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:客户端:调用实现

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值