面对对象的好处
通过封装、继承、多态把程序的耦合度降低。用设计模式是的程序更加的灵活,容易修改,并且易于复用。
实现一个简单的计算:
Operation运算类
public abstract class Operation {
private double NumberA = 0;
private double NumberB = 0;
public double getNumberA() {
return NumberA;
}
public void setNumberA(double numberA) {
NumberA = numberA;
}
public double getNumberB() {
return NumberB;
}
public void setNumberB(double numberB) {
NumberB = numberB;
}
public abstract double getResult() throws Exception;
}
加减乘除类:
class OperationAdd extends Operation{
@Override
public double getResult() {
// TODO Auto-generated method stub
double result = 0;
result = this.getNumberA() + this.getNumberB();
return result;
}
}
class OperationSub extends Operation{
@Override
public double getResult() {
// TODO Auto-generated method stub
double result = 0;
result = this.getNumberA() - this.getNumberB();
return result;
}
}
class OperationMul extends Operation{
@Override
public double getResult() {
// TODO Auto-generated method stub
double result = 0;
result = this.getNumberA() * this.getNumberB();
return result;
}
}
class OperationDiv extends Operation{
@Override
public double getResult() throws Exception {
// TODO Auto-generated method stub
double result = 0;
if(this.getNumberB() == 0){
throw new Exception("除数不能为0");
}
result = this.getNumberA() / this.getNumberB();
return result;
}
}
简单工厂类:
public class OperationFactory {
public static Operation createOperation(String operator){
Operation oper = null;
switch(operator){
case "+":
oper = new OperationAdd();break;
case "-":
oper = new OperationSub();break;
case "*":
oper = new OperationMul();break;
case "/":
oper = new OperationDiv();break;
}
return oper;
}
}
Main:
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Operation oper;
oper = OperationFactory.createOperation("/");
oper.setNumberA(1);
oper.setNumberB(0);
System.out.println(oper.getResult());
}
}