[设计模式]简单工厂模式

抽象工厂模式(abstract factory)

以简单的算术运算为例:

// 运算类
public abstract class Operation {
	public abstract int getResult(int numA, int numB);
}

// 加法运算类
public class OperationAdd extends Operation{
	@Override
	public int getResult(int numA, int numB) {
		return numA + numB;
	}
}


// 减法运算类
public class OperationSub extends Operation{
	@Override
	public int getResult(int numA, int numB) {
		return numA - numB;
	}
}


// 乘法运算类
public class OperationMul extends Operation{
	@Override
	public int getResult(int numA, int numB) {
		return numA * numB;
	}
}

// 除法运算类
public class OperationDiv extends Operation{
<span style="white-space:pre">	</span>@Override
<span style="white-space:pre">	</span>public int getResult(int numA, int numB) {
<span style="white-space:pre">		</span>if (numB == 0)
<span style="white-space:pre">			</span>throw new ArithmeticException("/ by zero");
<span style="white-space:pre">		</span>return numA / numB;
<span style="white-space:pre">	</span>}
}

// 运算工厂类
public class OperationFactory {
	public static Operation createOperate(String operate) {
		Operation operation = null;
		
		switch (operate) {
		case "+":
			operation = new OperationAdd();
			break;
			
		case "-":
			operation = new OperationSub();
			break;

		case "*":
			operation = new OperationMul();
			break;
			
		case "/":
			operation = new OperationDiv();
			break;
			
		default:
			break;
		}
		
		return operation;
	}
}


// 测试类
public class Test {
	public static void main(String[] args) {
		Operation add = OperationFactory.createOperate("+");
		System.out.println("1 + 2 = " + add.getResult(1, 2));
		
		Operation sub = OperationFactory.createOperate("-");
		System.out.println("1 - 2 = " + sub.getResult(1, 2));
		
		Operation mul = OperationFactory.createOperate("*");
		System.out.println("1 * 2 = " + mul.getResult(1, 2));
		
		Operation div = OperationFactory.createOperate("/");
		System.out.println("1 / 2 = " + div.getResult(1, 2));
	}
}

添加新的运算类时,只需要增加新的运算类以及修改运算工场类即可,不需要其他与之不相关的类,可以减少错误的修改,避免发生巨大的损失;

修改某个运算类时,直接修改运算类即可,不需要修改工厂类以及其他类,有效的降低了耦合度



你可能感兴趣的:(设计模式)