首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

设计模式-工厂模式

  • 1 简单工厂模式
代码语言:javascript
复制
package com.shi.design.factory.simplefactory;

/**
 * 把创建对象的过程交个工厂来实现
 * @author shiye
 *
 */
public class SimpleFactory {
	
	/**
	 *  根据输入对象的类行,来决定创建什么类
	 * @param type
	 * @return
	 */
	public static Operation createOperation(String type) {
		Operation option = null;
		
		switch (type) {
			case "+":
				option = new OperationAdd();
				break;
			case "-":
				option = new OperationSub();
				break;
			case "*":
				option = new OperationMul();
				break;
			case "/":
				option = new OperationDiv();
				break;
			default:
				break;
		}
		return option;
	}

}
  • 2 方法工厂模式
代码语言:javascript
复制
package com.shi.design.factory.methodfactory;

/**
 * 方法工厂模式:使用具体的子类来实现工厂模式
 * @author shiye
 *
 */
public class AddMethodFactory implements MethodFactory {

	@Override
	public Operation createOperation(String type) {
		return new OperationAdd();
	}

}
下一篇
举报
领券