Java设计模式 — 工厂模式(Factory)

工厂模式(Factory)

实例化对象,用工厂方法代替new操作。

介绍

  • 定义一个用于创建对象的接口,让子类决定实例化哪一个类。
  • 工厂方法使一个类的实例化延迟到其子类。

工厂模式要点:

简单工厂模式(静态工厂模式)
• 虽然某种程度不符合设计原则,但实际使用最多。
工厂方法模式
• 不修改已有类的前提下,通过增加新的工厂类实现扩展。
抽象工厂模式
• 不可以增加产品,可以增加产品族!

1.简单工厂模式

示例

接口定义

public interface Operation {
   
 
    public double getResult(double numberA,double numberB) throws Exception;
 
}

具体的实现类

public class Add implements Operation{
   
 
    // 加法计算
    public double getResult(double numberA, double numberB) {
   
 
        return numberA + numberB;
    }
}
 
public class Sub implements Operation{
   
 
    // 减法计算
    public double getResult(double numberA, double numberB) {
   
        return numberA-numberB;
    }
}
 
public class Mul implements Operation{
   
 
    // 乘法计算
    public double getResult(double numberA, double numberB) {
   
        return numberA * numberB;
    }
}
 
public class Div implements Operation {
   
 
    // 除法计算
    public double getResult(double numberA, double numberB) throws Exception {
   
        if (numberB == 0) {
   
            throw new Exception("除数不能为0!");
        }
        return numberA / numberB;
    }
}

简单工厂类

public class EasyFactory {
   
 
    // 简单工厂,根据字符串创建相应的对象
    public static Operation createOperation(String name) {
   
        Operation operationObj = null;
        switch (name) {
   
            case "+":
                operationObj = new Add();
                break;
            case "-":
                operationObj = new Sub();
                break;
            case "*":
                operationObj = new Mul();
                break;
            case "/":
                operationObj = new Div();
                break
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值