开放封闭原则感觉不错,其核心就是:面对需求,对程序的改动是通过增加代码来进行的,而非修改现有代码。
一个计算类,如果新增加减乘除运算,都只需要继承Calculator,新增子类即可,而不用在Calculator类内部修改。
abstract class Calculator
{
double numA;
double numB;
public abstract double getResult();
}
class Add extends Calculator
{
public Add(double numA,double numB)
{
this.numA=numA;
this.numB=numB;
}
@Override
public double getResult() {
// TODO Auto-generated method stub
return numA+numB;
}
}
class Minus extends Calculator
{
public Minus(double numA,double numB)
{
this.numA=numA;
this.numB=numB;
}
@Override
public double getResult() {
// TODO Auto-generated method stub
return numA-numB;
}
}
public class OpenClosed {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator c;
c=new Add(10,5);
System.out.println("Add:"+c.getResult());
c=new Minus(10,5);
System.out.println("Minus:"+c.getResult());
}
}