设计模式-工厂模式

2019-08-12 17:29:51 浏览数 (1)

  • 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();
	}

}

0 人点赞