用于装饰类的私有方法的模式

本文关键字:模式 有方法 用于 | 更新日期: 2023-09-27 17:51:18

在下面的类中,我有一个名为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
    }
}

谢谢。

用于装饰类的私有方法的模式

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

祝你好运!