单一职责原则
不要存在多于一个导致类变更的原因;
一个类/接口/方法只负责一项职责;
类的单一职责示例
- 类Bird是违反单一职责原则的;
- 从类的角度将类拆分成职责更小的多个类;
- 类WalkBird和FlyBird是符合单一职责原则的;
public class Bird {
public void mainMoveMode(String birdName){
if("鸵鸟".equals(birdName)){
System.out.println(birdName+"用脚走");
}else{
System.out.println(birdName+"用翅膀飞");
}
}
}
public class WalkBird {
public void mainMoveMode(String birdName){
System.out.println(birdName+"用脚走");
}
}
public class FlyBird {
public void mainMoveMode(String birdName){
System.out.println(birdName+"用翅膀飞");
}
}
接口的单一职责示例
- 每个接口定义的功能更单一,组合起来会灵活很多;
public interface ICourse {
String getCourseName();
byte[] getCourseVideo();
void studyCourse();
void refundCourse();
}
public interface ICourseContent {
String getCourseName();
byte[] getCourseVideo();
}
public interface ICourseManager {
void studyCourse();
void refundCourse();
}
方法的单一职责示例
- 避免长度太长的大方法,更倾向于多个短小的小方法,像updateUsername,updateUserAddress这样的,意义更明确的短小方法;
- 方法updateUsername和updateUserAddress是符合单一职责原则的;
public class Method {
private void updateUserInfo(String userName,String address){
userName = "geely";
address = "beijing";
}
private void updateUserInfo(String userName,String... properties){
userName = "geely";
// address = "beijing";
}
private void updateUsername(String userName){
userName = "geely";
}
private void updateUserAddress(String address){
address = "beijing";
}
private void updateUserInfo(String userName,String address,boolean bool){
if(bool){
//todo something1
}else{
//todo something2
}
}
}