传统的controller + server + dao
A B C三个模块看上去是分离的,实际上8个模块之间存在相互依赖的关系,并不是一个高内聚而是一个低内聚的形式。
DIP(依赖反转)模式
设计一 低级组件和高级组件都作为具体类放在同一个包里面
public class StringProcessor { //具体类
private final StringReader stringReader; //具体类
private final StringWriter stringWriter; //具体类
//通过构造函数来注入依赖组件
public StringProcessor(StringReader stringReader, StringWriter stringWriter) {
this.stringReader = stringReader;
this.stringWriter = stringWriter;
}
public void readAndWrite() {
stringWriter.write(stringReader.getValue());
}
//测试用例
public static void main(String[] args) {
StringReader sr = new StringReader();
sr.read("1111111");
StringWriter sw = new StringWriter();
StringProcessor sp = new StringProcessor(sr,sw);
sp.readAndWrite();
}
}
设计二 低级组件具体类与高级组件接口实现类放在同一程序包
面向接口设计编程
public interface StringProcessor {
void readAndWrite(StringReader stringReader, StringWriter stringWriter);
}
public class StringProcessorImpl implements StringProcessor {
//通过接口传参来注入依赖组件
@Override
public void readAndWrite(StringReader stringReader, StringWriter stringWriter) {
stringWriter.write(stringReader.getValue());
}
public static void main(String[] args){
StringReader sr = new StringReader();
sr.read("222222");
StringWriter sw = new StringWriter();
StringProcessor sp = new StringProcessorImpl();
sp.readAndWrite(sr,sw);
}
}
设计三: 低级组件接口类与高级组件接口实现类放在同一程序包中
将StringReader 和StringWriete 进行抽象
public interface StringReader {
void read(String path);
String getValue();
}
public interface StringWriter {
void write(String value);
}
原先的类型变为接口(抽线了出来)
public class StringProcessorImpl implements StringProcessor {
//StringReader 是接口
//StringWriter 是接口
@Override
public void readAndWrite(StringReader stringReader, StringWriter stringWriter) {
stringWriter.write(stringReader.getValue());
}
public static void main(String[] args) {
StringReader sr = new StringReaderImpl();
sr.read("333333");
StringWriter sw = new StringWriterImpl();
StringProcessor sp = new StringProcessorImpl();
sp.readAndWrite(sr,sw);
}
}
设计四 低级组件接口与高级组件接口类放在不同包中
sprin 框架注入
public class SPTest {
@Resource
private StringProcessor sp;
@Resource
private StringReader sr;
@Resource
private StringWriter sw;
public void main(String[] args) {
sr.read("444444");
sp.readAndWrite(sr,sw);
}
}
分层
架构设计视角下的关注点分离更重视组件之间的分离,并通过一定的通信策略来保证架构内各个组件间的相互引用。