大话设计模式
1.9紧耦合vs松耦合
1.10简单工厂模式
自己写的java代码
package btdp.one.night;
/**
* desc:抽象类-操作类
* Date: 2018-08-15
* @author szq
*
*/
public abstract class Operation {
double numberA;
double numberB;
public abstract double result() throws Exception;
}
package btdp.one.night;
/**
* desc:加法类
* date:2018.08.15
* @author szq
*
*/
public class OperationAdd extends Operation {
@Override
public double result() {
return numberA + numberB;
}
}
package btdp.one.night;
/**
* desc:减法类
* date:2018.08.15
* @author szq
*
*/
public class OperationSub extends Operation {
@Override
public double result() {
return numberA - numberB;
}
}
package btdp.one.night;
/**
* desc:乘法类
* date:2018.08.15
* @author szq
*
*/
public class OperationMul extends Operation {
@Override
public double result() {
return numberA * numberB;
}
}
package btdp.one.night;
/**
* desc:除法类
* date:2018.08.15
* @author szq
*
*/
public class OperationDiv extends Operation {
@Override
public double result() throws Exception {
if (numberB == 0) {
throw new Exception("除数不能为0");
}
return numberA / numberB;
}
}
package btdp.one.night;
/**
* desc:使用简单工厂模式
* date:2018.08.15
* @author szq
*
*/
public class OperationFactory {
public static Operation createOperate(char operate) {
Operation oper = null;
switch (operate) {
case ‘+’:
oper = new OperationAdd();
break;
case ‘-‘:
oper = new OperationSub();
break;
case ‘*’:
oper = new OperationMul();
break;
case ‘/’:
oper = new OperationDiv();
break;
}
return oper;
}
}
package btdp.one.night;
/**
* desc:客户端类计算加减乘除
* date:2018.08.15
* @author szq
*
*/
public class Client {
public static void main(String[] args) throws Exception {
Operation oper;
oper = OperationFactory.createOperate(‘+’);
oper.numberA = 234;
oper.numberB = 123;
double result = oper.result();
System.out.println(result);
}
}