我有一个Windows服务应用程序,可以读取一些文件并进行一些修改并将其上传到Web API。
在这里,我尽可能遵循单一责任原则。
在此应用程序中,我有3个类来读取文件的内容,应用业务逻辑并将修改后的内容上载到服务器。
class GetFileContent {
// in here there is a method to return the file content
}
class ApplyBusinessLogic {
// in here there is a method to get that file content as param and apply business logic
}
class UploadContent {
// get the modified content and upload it
}
现在我的问题是,如果我添加一个新类作为
DoMyActions
并创建上述类的对象并调用theres方法来执行这些任务,是否违反了单一职责原则?为了弄清楚我的问题,我想做以下类似的事情。class DoMyAction {
GetFileContent content = new GetFileContent();
// call the method in above class and get the content
ApplyBusinessLogic doMyThing = new ApplyBusinessLogic();
// do my stuff using that file content
UploadContent uploader = new UploadContent();
// upload the content
}
有更好的办法吗?
如果我一直想使用
DoMyAction
类,该如何遵循“单一责任原则”? 最佳答案
如果DoAction
类过程不变,则可以直接将GetFileContent
,ApplyBusinessLogic
,UploadContent
封装到DoAction
类中。
但是我会为每个类创建接口以使代码更灵活。
public interface IFileContent{
byte[] GetFileContent();
}
public interface IApplyBusinessLogic{
void ApplyLogic();
}
public interface IUploadContent{
void Upload();
}
然后,每个类都实现与它的操作匹配的每个接口。
public class GetFileContent : IFileContent {
public byte[] GetFileContent(){
}
// in here there is a method to return the file content
}
public class ApplyBusinessLogic : IApplyBusinessLogic {
public void ApplyLogic(){
}
// in here there is a method to get that file content as param and apply business logic
}
public class UploadContent : IUploadContent{
public void Upload(){
}
// get the modified content and upload it
}
然后,我将使用构造函数注入来注入procedure,类使代码更加灵活。
public class DoMyAction {
IFileContent _content;
// call the method in above class and get the content
IApplyBusinessLogic _doMyThing;
// do my stuff using that file content
IUploadContent _uploader;
// upload the content
public DoMyAction(IFileContent content,IApplyBusinessLogic doMyThing,IUploadContent uploader){
_content = content;
_doMyThing = doMyThing;
_uploader = uploader;
}
public void excuteAPI(){
//doing something here
}
}
您可以在
excuteAPI
类的DoMyAction
方法中设置执行逻辑。