我有一些代码我想重新考虑因素,所以它不违反单一责任原则(SRP)。
据我所知,以下课程可能因多种原因而改变:
但是,我很难搞清楚如何重新考虑到不同的课程。
Engine.java
package com.example;
import java.util.List;
public interface Engine {
public List<Recording> analyze(List<String> files);
public List<Recording> getMetadata(List<Recording> recordings);
public List<Recording> upload(List<Recording> recordings);
}
CallEngine.java
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CallEngine implements Engine {
final static Logger log = LoggerFactory.getLogger(Main.class);
public List<Recording> analyze(List<String> files) {
log.info("Analyzing recording files per business rules...");
List<Recording> recordings = new ArrayList<Recording>();
return recordings;
}
public List<Recording> getMetadata(List<Recording> r) {
log.info("Retrieving metadata for calls...");
List<Recording> recordings = new ArrayList<Recording>();
return recordings;
}
public List<Recording> upload(List<Recording> r) {
log.info("Uploading calls...");
List<Recording> recordings = new ArrayList<Recording>();
return recordings;
}
}
答案 0 :(得分:1)
public interface Analyzer {
public void analyze();
}
public interface Retriever {
public void retrieveMetadata();
}
public interface Uploader {
public void upload();
}
public class EngineAnalyzer implements Analyzer {
final static Logger log = LoggerFactory.getLogger(Main.class);
public List<Recording> recordings;
EngineAnaylzer(List<String> Files) {
}
public void analyze() {
log.info("Analyzing recording files per business rules...");
}
}
答案 1 :(得分:1)
SRP主要通过抽象接口后面的代码并将不相关功能的责任委托给运行时接口后面的任何实现来实现。
在这种情况下,您需要在自己的界面后面抽象出责任。
例如......
public interface Analyzer {
public List<Recording> analyze(List<String> files);
}
public interface Retriever {
public List<Recording> getMetadata(List<Recording> recordings);
}
public interface Uploader {
public List<Recording> upload(List<Recording> r);
}
并将它们作为Engine
实现的可注入依赖项。
public class CallEngine implements Engine {
private Analyzer analyzer;
private Retriever retriever;
private Uploader uploader;
public CallEngine(Analyzer analyzer, Retriever retriever, Uploader uploader) {
this.analyzer = analyzer;
this.retriever = retriever;
this.uploader = uploader;
}
public List<Recording> analyze(List<String> files) {
return analyzer.analyze(files);
}
public List<Recording> getMetadata(List<Recording> r) {
return retriever.getMetadata(r);
}
public List<Recording> upload(List<Recording> r) {
return uploader.upload(r);
}
}
可以更改它们的运行时实现,而不会影响依赖类实现的整体责任,这使得它更适应变化。