c# - 不断地让新的对象正常吗?

标签 c# single-responsibility-principle

答案:尽管将类转为变量然后调用它们会起作用,但在这种情况下,这可能是设计不良的标志。更好的设计会产生副作用,即不需要一开始就不断创建类的新实例。

============

最近我一直(尝试)将 SRP 应用到我的代码中,将所有职责拆分到单独的类中。它工作得很好,代码的可维护性和可重用性提高了很多……但我发现自己一直在做类似 new Table.Type("messages").Get(id); 的事情。

我的大部分类都只包含一个方法。还是。。感觉很尴尬。胆量说这是我不妨将它们全部变成静态类的地步。

所以我想我应该求助于我更有经验的前辈,经常写“new Class().Method()”是不是很常见?或者有更好的处理方法吗?

示例代码:

public void AdminCommands(Channel channel, IrcUser user, string message)
{
    var command = message.Split(' ')[0];
    switch (command)
    {
        case "@info":
            GetInfo(channel, message);
            break;
        //----a couple of more commands
    }
}

private void GetInfo(Channel channel, string message)
{
    Match match = Regex.Match(message, "@info (.+)");
    if (match.Success)
    {
        string search = match.Groups[1].Value;
        //Get stored data on the word or sentence, and send the result to chat.
        new CommandInfo().Execute(search);  //<-------------------- over here.
        return;
    }
    Chat.SendAdminMessage("Message not found.");
}
private void EditMessage(Channel channel, string message)
{
    Match match = Regex.Match(message, "@edit (.+?) (.+?) (.+?)=(.+)");
    if (match.Success)
    {
        string type = match.Groups[1].Value;
        string id = match.Groups[2].Value;
        string toReplace = match.Groups[3].Value;
        string replaceWith = match.Groups[4].Value;

        //Gets message of 'type' by 'id', and store it back after editing.
        new CommandEdit().Execute(type, id, toReplace, replaceWith); //<-here.
    }
}

最佳答案

当然可以将CommandEdit和CommandInfo存储为成员变量,然后调用Execute

private CommandInfo mInfo = new CommandInfo();

private void GetInfo(Channel channel, string message)
{
    Match match = Regex.Match(message, "@info (.+)");
    if (match.Success)
    {
        string search = match.Groups[1].Value;
        //Get stored data on the word or sentence, and send the result to chat.
        mInfo.Execute(search);  //<-------------------- over here again.
        return;
    }
    Chat.SendAdminMessage("Message not found.");
}

关于c# - 不断地让新的对象正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22046321/

相关文章:

c# - 在这种情况下使用多态性优于枚举有什么好处吗?

separation-of-concerns - 单一责任原则与关注点分离的区别

ruby-on-rails - 清理 fat rails 助手

c# - 单一职责原则是否与类的依赖关系直接相关?

c# - IoC、SRP 和组合——我是否创建了太多接口(interface)?

dependency-injection - setter 和 getter 真的会破坏 SRP 吗?

c# - 在 C# 中解析 C 头文件

c# - 如何在 WPF WebBrowser 中使用 'Back' 和 'Forward' 导航按钮事件?

C# 方法原型(prototype)就像 C++ 中的方法原型(prototype)

c# - 如何在 AWS Lambda C# 实现中使用依赖注入(inject)