单一职责原则笔记
程序员文章站
2024-03-16 22:13:04
...
以下以类说明单一职责原则(接口,方法同理)
单一职责原则,通俗来说,一个类只负责一项任务。
以前我们用一个类来说明鸟飞行的方式时,先判断鸟的类型,然后输出方法。例如以下代码:
Bird类
public class Bird {
public void mainMoveMode(String birdName){
if("鸵鸟".equals(birdName)){
System.out.println(birdName+"用脚走");
}else{
System.out.println(birdName+"用翅膀飞");
}
}
}
Test主类
public class Test {
public static void main(String[] args) {
Bird bird = new Bird();
bird.mainMoveMode("大雁");
bird.mainMoveMode("鸵鸟");
}
}
当鸟类的种类少时,可能程序不太紧要。但随着鸟类的种类数目越来越多时,边界判断就越来越大,变更时的风险就越大。
现在将Bird类拆分,分为WalkBird 和FlyBird两类.
WalkBird类
public class WalkBird {
public void mainMoveMode(String birdName){
System.out.println(birdName+"用脚走");
}
}
FlyBird类
public class FlyBird {
public void mainMoveMode(String birdName){
System.out.println(birdName+"用翅膀飞");
}
}
Test主类
public class Test {
public static void main(String[] args) {
// Bird bird = new Bird();
// bird.mainMoveMode("大雁");
// bird.mainMoveMode("鸵鸟");
FlyBird flyBird = new FlyBird();
flyBird.mainMoveMode("大雁");
WalkBird walkBird = new WalkBird();
walkBird.mainMoveMode("鸵鸟");
}
}
结构图: