gpt4 book ai didi

c# - 如何在一组 Action 中遵循单一职责原则

转载 作者:行者123 更新时间:2023-11-30 21:31:15 26 4
gpt4 key购买 nike

我有一个 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 类。

但我会为每个类创建接口(interface),让代码更灵活。

public interface IFileContent{
byte[] GetFileContent();
}
public interface IApplyBusinessLogic{
void ApplyLogic();
}
public interface IUploadContent{
void Upload();
}

然后每个类实现每个接口(interface),这与其 Action 相匹配。

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
}

然后我会使用constructor injection来注入(inject)proceed,class让代码更灵活。

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
}
}

您可以在 DoMyAction 类的 excuteAPI 方法中设置您的执行逻辑。

关于c# - 如何在一组 Action 中遵循单一职责原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53474193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com