开发者

Should the factory pattern be used to disable functionality?

I'm trying to get my head around the usage of the factory pattern, when I wish to disable features within an application.

Lets say for example I have a factory called LoggerFactory, which creates a logger instance.

If in the configuration logging is disabled in my application:

Should the logger factory pass back an instance of the logger that is a dummy, that doe开发者_如何学JAVAsn't do anything? So any code using the logger does not need to change.

Or, is it the responsibility of the code using the logger, not to use the logger if it is disabled in the configuration?

Or, is it the responsibility of the logger itself not to do anything, if it is disabled?

Thanks for the help.


If you have many different logger-classes (e.g. log to file and log to network) then I think returning a dummy logger when logging is disabled is the simplest and most flexible solution. It will require no change to the code that uses the logger, and it will require no changes to the other loggers.

The idea of making the user of the logger responsible is bad, as that would spread the feature of disabling the logging through the entire code, thus polluting application logic.


IMHO, that's not a question about the principles of the factory pattern. It's more a question about the design of your coding style etc. But, just to provide an answer regarding your conrete question: It would be easier and more intuitive and more flexible (1) to return an object as an instance of an "empty" logger class or (2) to check the logging-disabled-flag within the regular logger class.


The code using the logger should not be involved in the enabled/disabled conditionality.

As to whether to use a Dummy disabled logger or just a stadanrd logger that knows it's disabled that's less obvious. Pragmatically I suspect that we'll tend to find that partial enablement is the most common scenario - some destinations or message classes will tend to be emitted when most are disabled. So I'd probably see this as the natural job of the logger to understand what it's configured to do.

I would go with the dummy only if this makes logger implementation very much easier and it's a common usage scenario.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜