【JAVA设计模式】简单工厂模式

一、定义

简单工厂模式关注的问题是如何去实例化对象,到底要实例化谁,将来会不会增加实例化的对象。被创建实例的类型可以是接口、抽象类,也可以是具体的类。

二、UML类图

简单工厂模式UML类图

三、实现

  • 操作父类
package com.jthao.design.des.factory;

public class Operation {

	private static double numberA;

	private static double numberB;

	public double getResult() {
		double result = 0;
		return result;
	}

	public static double getNumberA() {
		return numberA;
	}

	public void setNumberA(double numberA) {
		Operation.numberA = numberA;
	}

	public double getNumberB() {
		return numberB;
	}

	public void setNumberB(double numberB) {
		Operation.numberB = numberB;
	}

}
  • 具体操作类A
package com.jthao.design.des.factory;

public class OperationAdd extends Operation {

	@Override
	public double getResult() {
		double result = 0;
		result = getNumberA() + getNumberB();
		return result;
	}

}
  • 具体操作类B
package com.jthao.design.des.factory;

public class OperationDiv extends Operation {

	@Override
	public double getResult() {
		double result = 0;
		result = getNumberA() / getNumberB();
		return result;
	}

}
  • 常量类
package com.jthao.design.des.factory;

public enum OperationEnum {

	add("1"), sub("2"), mul("3"), div("4");

	String value = "";

	private OperationEnum(String value) {
		this.value = value;
	}

	public String getValue() {
		return this.value;
	}

}
  • 工厂类
package com.jthao.design.des.factory;

public class OperationFactory {

	public static Operation createOperation(OperationEnum operationEnum) {
		Operation operation = null;
		switch (operationEnum) {
		case add:
			operation = new OperationAdd();
			break;
		case div:
			operation = new OperationDiv();
			break;
		default:
			break;
		}
		return operation;
	}

}
  • 测试类
package com.jthao.design.des.factory;

public class FactoryTest {

	public static void main(String[] args) {
		Operation operation = new Operation();
		operation.setNumberA(10.0);
		operation.setNumberB(20.0);
		operation = OperationFactory.createOperation(OperationEnum.add);
		System.out.println(operation.getResult());
	}

}

四、更多文章阅读

【SpringCloud Greenwich版本】汇总
【JAVA设计模式】汇总

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值