1.依赖倒置原则
A.高层次的模块不应该依赖于低层次的模块,他们都应该依赖于抽象。
B.抽象不应该依赖于具体,具体应该依赖于抽象。
2.用UML图来说明一下:
代码说明:
(1)管理员接口
1 package com.alibaba.com.miao; 2 3 public interface IEmployee { 4 5 public String code(ICode code); 6 }
(2)编码接口
1 package com.alibaba.com.miao; 2 3 public interface ICode { 4 5 public String getRun(String Run); 6 }
(3)编码类
1 package com.alibaba.com.miao; 2 3 public class Code implements IEmployee { 4 5 private static final String Run = "编码活动"; 6 7 @Override 8 public String code(ICode code) { 9 10 System.out.println(code + "程序员开始编码..."); 11 12 return code.getRun(Run); 13 } 14 }
(4)普通程序员
1 package com.alibaba.com.miao; 2 3 public class CommonProgrammer implements ICode { 4 5 private static final String Run = "JACK"; 6 7 @Override 8 public String getRun(String Run1) { 9 String Run2 = "工作"; 10 System.out.println(Run + " 普通程序员开始工作"); 11 return Run2; 12 } 13 14 }
1 package com.alibaba.com.miao; 2 3 public class SeniorProgrammer implements ICode { 4 5 private static final String Run = "李四"; 6 7 @Override 8 public String getRun(String Run1) { 9 String Run2 = "工作"; 10 return Run2; 11 } 12 13 }
1 <%@page import="com.alibaba.com.miao.ICode"%> 2 <%@page import="com.alibaba.com.miao.CommonProgrammer"%> 3 <%@page import="com.alibaba.com.miao.SeniorProgrammer"%> 4 <%@page import="com.alibaba.com.miao.Code"%> 5 <%@page import="com.alibaba.com.miao.IEmployee"%> 6 <%@ page language="java" contentType="text/html; charset=UTF-8" 7 pageEncoding="UTF-8"%> 8 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 9 <html> 10 <head> 11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 12 <title>单一职责原则</title> 13 </head> 14 <body> 15 16 <% 17 IEmployee employee = new Code(); 18 19 ICode code = new SeniorProgrammer(); 20 ICode code1 = new CommonProgrammer(); 21 22 out.println(" " + employee.code(code)); 23 out.println("管理人员派张三高级程序员" + employee.code(code1)); 24 %> 25 26 </body> 27 </html>
(7)参考目录结构
参考:Java Web设计模式之道。