开发者

Chain of Responsibility Logging

开发者 https://www.devze.com 2023-03-29 07:39 出处:网络
I have an abstract class called ChainHandler and many implementations of the ChainHandler. Other programmers will write other implementations of that ChainHandler.

I have an abstract class called ChainHandler and many implementations of the ChainHandler.

Other programmers will write other implementations of that ChainHandler.

My program implements the Chain of Responsibility design pattern.

Each concrete implementation of the ChainHandler implements a handle method.

public abstract void handle(SomeclassA a);

If one handler can handle "a", it handles it and the chain stops. If not,"a" is passed to the next Handler until it hits the end of the chain.

I want each concr开发者_运维问答ete handler to have a list of all "a"s it was able to handle. But I don't want to make the concrete classes developer to remember to write it to a list on success.

Is there a elegant way of doing it?

My best idea was the following:

1 - Change the handle method to protected at the concrete classes, make it return a boolean and change the name to innerhandle;

2 - Change the handle method at the abstract class to public and it calls the innerhandle. On success, it adds the object to the list.


The second option is surely better (and it relies on the Template method pattern) making it harder for someone implementing a subclass of doing it wrong, you can even make the handle method final so no one will ever be able to change it's behavior and break without noticing it.

The servlet API has such an example, the init method that takes a ServletConfig parameter can be overridden and it's rather common to see people forgetting to call super and the original init(ServletConfig) method, so you should try to avoid this same mistake.

0

精彩评论

暂无评论...
验证码 换一张
取 消