单一职责原则
发布时间:2020-12-14 05:03:55 所属栏目:百科 来源:网络整理
导读:1.定义:不要存在多于一个导致类变更的原因 2.一个类/接口/方法只负责一项职责 3.优点:降低类的复杂度、提高类的可读性,提高系统的可维护性、降低变更引起的风险 4.实例目录package 5.实例UML类图 6.代码 1 package com.geely.design.principle.signleresp
1.定义:不要存在多于一个导致类变更的原因 2.一个类/接口/方法只负责一项职责 3.优点:降低类的复杂度、提高类的可读性,提高系统的可维护性、降低变更引起的风险 4.实例目录package 5.实例UML类图 6.代码 1 package com.geely.design.principle.signleresponsibility; 2 3 public class Bird { 4 5 public void mainMoveMode(String birdName){ 6 if("鸵鸟".equals(birdName)){ 7 System.out.println(birdName + "用脚走"); 8 }else{ 9 System.out.println(birdName + "用翅膀飞"); 10 } 11 } 12 } 1 package com.geely.design.principle.signleresponsibility; 2 3 public class FlyBird { 4 public void mainMoveMode(String birdName){ 5 System.out.println(birdName + "用翅膀飞"); 6 } 7 } 1 package com.geely.design.principle.signleresponsibility; 2 3 public class WalkBird { 4 public void mainMoveMode(String birdName){ 5 System.out.println(birdName + "用脚走"); 6 } 7 } 1 package com.geely.design.principle.signleresponsibility; 2 3 public class Test { 4 public static void main (String[] args){ 5 /*Bird bird = new Bird(); 6 bird.mainMoveMode("大雁"); 7 bird.mainMoveMode("鸵鸟");*/ 8 9 FlyBird flyBird = new FlyBird(); 10 flyBird.mainMoveMode("大雁"); 11 WalkBird walkBird = new WalkBird(); 12 walkBird.mainMoveMode("鸵鸟"); 13 } 14 } 1 package com.geely.design.principle.signleresponsibility; 2 3 public interface ICourse { 4 String getCourseName(); 5 byte[] getCourseVideo(); 6 7 void studyCourse(); 8 void refundCourse(); 9 } 1 package com.geely.design.principle.signleresponsibility; 2 3 public interface ICourseContent { 4 String getCourseName(); 5 byte[] getCourseVideo(); 6 } 1 package com.geely.design.principle.signleresponsibility; 2 3 public interface ICourseManager { 4 void studyCourse(); 5 void refundCourse(); 6 } package com.geely.design.principle.signleresponsibility; public class CourseImpl implements ICourseManager,ICourseContent{//ICourse public String getCourseName() { return null; } public byte[] getCourseVideo() { return new byte[0]; } public void studyCourse() { } public void refundCourse() { } } 1 package com.geely.design.principle.signleresponsibility; 2 3 public class Method { 4 private void updateUserInfo(String userName,String address){ 5 userName = "geely"; 6 address = "beijing"; 7 } 8 private void updateUserInfo(String userName,String ... properties){ 9 userName = "geely"; 10 //address = "beijing"; 11 } 12 13 private void updateUserName(String userName){ 14 userName = "geely"; 15 } 16 private void updateAddress(String address){ 17 address = "beijing"; 18 } 19 20 private void updateUserInfo(String userName,String address,boolean bool){ 21 if(bool){ 22 //todo something1 23 }else{ 24 //todo something2 25 } 26 userName = "geely"; 27 address = "beijing"; 28 } 29 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |