【问题标题】:Patterns for decorating private methods of a class装饰类的私有方法的模式
【发布时间】:2015-06-01 12:12:34
【问题描述】:

在下面的类中,我有一个名为 ProcessMessage 的公共方法。此方法负责处理传入的消息。处理消息涉及不同的阶段。我想以这样一种方式装饰这个类,以便我可以从消息处理的每个阶段发布性能计数器值。

我知道我可以重写 ProcessMessage 方法并使用发布性能计数器值再次重写逻辑。但是有没有更好的方法/模式可以应用,这样我就不必在装饰类中再次复制逻辑。

public class MessageProcessor
{

    public void ProcessMessage()
    {
        ConvertReceivedMessage();
        SendToThirdParty();
        ReceiveResponse();
        ConvertResponseMessage();
        SendResponseToClient();
    }

    private void ConvertReceivedMessage()
    {
        //here I want to publish the performance counter value from the decorated class
    }
    private void SendToThirdParty()
    {
         //here I want to publish the performance counter value from the decorated class

    }
    private void ReceiveResponse()
    {
         //here I want to publish the performance counter value from the decorated class

    }
    private void ConvertResponseMessage()
    {
         //here I want to publish the performance counter value from the decorated class

    }

    private void SendResponseToClient()
    {
         //here I want to publish the performance counter value from the decorated class

    }

}

谢谢。

【问题讨论】:

  • 什么是性能计数器功能?
  • 为什么不使用组合,而只使用 MessageProcessor 类呢?然后只调用新类中的 ProcessMessage() 方法?
  • 你的装饰器是直接调用MessageProcessor.ProcessMessage还是继承自MessageProcessor
  • 可以不保护方法,每个方法都被覆盖,你的性能计算,调用基类方法吗?不是理想的解决方案,但可能是一种选择。
  • 我的装饰器继承自 MessageProcessor 。我没有 MessageProcessor 类的源代码来更改实现。

标签: c# design-patterns decorator


【解决方案1】:

使用 IProcessor 对象列表而不是一堆方法。这样您就可以添加/跳过/更改呼叫顺序。在您的 IProcessor 中声明 Process(PerformanceContext context) 方法并实现 PerformanceContext 类以交换一些值,例如 StartTime、NumberOfCalls 等。

祝你好运!

【讨论】:

  • 感谢 Denis,我要求我的供应商按照您建议的方式提供课程。我还根据您的建议做了一个小型 POC,它奏效了。
猜你喜欢
  • 2014-12-29
  • 1970-01-01
  • 2021-10-10
  • 2012-01-28
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
相关资源
最近更新 更多