开发者

Should a parent class ever reference child classes?

开发者 https://www.devze.com 2023-01-27 05:24 出处:网络
Good morning, I inherited some legacy code at work and it is using a rather unusual design pattern. The only reference I could find on the forums to a similar pattern was here. The situation is that

Good morning,

I inherited some legacy code at work and it is using a rather unusual design pattern. The only reference I could find on the forums to a similar pattern was here. The situation is that the original designer has a generic parent class (not abstract) that has a static factory method which directly references children classes.

Here is a sample of that style of coding, found in several places in the legacy code:

public static LoggerFactory getLoggerFactory(LogType type) {
    switch (type) {
    case LOG4J:
        return Log4JLoggerFactory.getInstance();开发者_JAVA技巧
    case LOGBACK:
        return LogBackLoggerFactory.getInstance();
    default:
        throw new RuntimeException("No logger factory defined for type " + type);
    }
}

Where Log4JLoggerFactory and LogBackLoggerFactory extend LoggerFactory.

This seems really foreign to me but before I re-factor the code significantly, is there any purpose or benefit to this design pattern (is there even a formal name for it)?

Any thoughts or advice is appreciated. Thanks!

EDIT: After reading Yishai's response, I thought I would include a link to the Wikipedia article on the Strategy pattern, for easy reference. Thanks to everyone for your responses!


It's a very standard pattern in Java, and a common way to implement a Strategy pattern. You see it in the standard API all the time (Calendar vs. GregorianCalendar, NumberFormat vs. DecimalFormat and more).

That being said, with Dependency Injection being all the rage, such a pattern might indeed be replaced by a dedicated Factory class with a dedicate Factory interface, but in the absence of a larger design reason, I think the example you give is a perfectly reasonable design choice.


It is a good practise and called Factory Method.

The benefit is that you return some concrete implementation but hide it via common interface or base class. Thus client isn't bothered by implementation details, but works with a most basic class.


Maybe they have it setup that way to use Log4J in one environment, and Logback in another? I know sometimes developers prefer a tool when doing local development, but when it comes time to deploy have to use whatever the company endorses/approves.


Whether this is a good or bad practice it depends on situation. Eg when the 'parent' knows how to create all the children, it may be a good practice. When the parent doesn't know it, this solution will only cause trouble.

Another problem is testability: if parent has lots of children, it may be hard to create parent in isolation from the children, but again it depends.

0

精彩评论

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