Java大话设计模式学习总结(八)---工厂方法模式

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

来自大话设计模式

用之前简单工厂模式做的计算器举例,先看简单工厂模式的实现:

// 运算类
public abstract class Operation {
	protected int numberA;
	protected int numberB;
	protected abstract String getResult();
}

// 工厂类
public class OperFactory {

	public static Operation createOper(String oper) {
		Operation operation = null;
		switch (oper) {
		case "+":
			operation = new Add();
			break;
		case "-":
			operation = new Sub();
			break;
		case "*":
			operation = new Mul();
			break;
		case "/":
			operation = new Div();
			break;

		default:
			break;
		}
		return operation;
	}
}

// 加法运算类,减、乘法运算类似
public class Add extends Operation {
	@Override
	protected String getResult() {
		return String.valueOf(numberA + numberB);
	}
}

// 除法运算类类
public class Div extends Operation {
	@Override
	protected String getResult() {
		return String.valueOf( numberB == 0 ? "除数不能为0" : (float)numberA / numberB);
	}
}

工厂模式就是将之前的工厂类OperFactory变为一个工厂接口,然后加减乘除各建一个具体工厂去实现这个接口:

public interface IFactory {
    Operation createOperation();
}

public class AddFactory implements IFactory {
    @Override
    public Operation createOperation() {
        return new Add();
    }
}

public class DivFactory implements IFactory {
    @Override
    public Operation createOperation() {
        return new Div();
    }
}

下面来对比一下简单工厂模式和工厂模式的调用方法:

// 简单工厂模式
public class Calculate {
	public static void main(String[] args) {
		Operation oper = OperFactory.createOper("/");
		oper.numberA = 7;
		oper.numberB = 3;
		System.out.println(oper.getResult());
	}
}

// 工厂模式
public class Calculate {
    public static void main(String[] args) {
        IFactory operFactory = new DivFactory();
        Operation operation = operFactory.createOperation();
        operation.numberA = 7;
        operation.numberB = 3;
        System.out.println(operation.getResult());
    }
}

可以看出来,如果需要增加其他的运算方法,使用简单工厂模式时,工厂类OperFactory需要对原有的代码进行修改,就违背了开放-封闭原则。而采用工厂模式时,只需要增加一个新算法的工厂实现类,在调用时采用new NewOperationFactory()就可以采用新的算法进行计算了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值