违反开闭原则的例子,代码及改正方法:
//水果类Fruits
class Fruits
{
private int num;
void setI(int n)
{
num=n;
}
int getN()
{
return num;
}
void eat()
{
num=num-1;
}
};
//嘴类Mouth
class Mouth
{
public Fruits fruit;
void do()
{
if(fruit.getN()!=0)
{
fruit.eat();
System.out.println("水果数量为:"+fruit.getN());
}
else
{
System.out.println("没有水果!");
break;
}
}
};
public class aa {
public static void main(String[] args) {
Mouth m=new Mouth();
m.fruit=new Fruits();
m.fruit.setI(5);
m.do();
}
}
运行结果:
改正方法: