父类是否应该引用子类? [英] Should a parent class ever reference child classes?

查看:119
本文介绍了父类是否应该引用子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,



我在工作中继承了一些遗留代码,它使用了一种非常不寻常的设计模式。我可以在论坛上找到类似模式的唯一参考资料是这里。情况是,原始设计师有一个通用的父类(不是抽象的),它具有直接引用子类的静态工厂方法。



这是一个样式的编码,在遗留代码的几个地方找到:

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

其中Log4JLoggerFactory和LogBackLoggerFactory扩展LoggerFactory。



这似乎对我来说很外在,但在我重新确定代码之前,这个设计模式有什么目的或好处(甚至有一个正式的名字)? p>

任何想法或建议不胜感激。谢谢!



编辑:阅读沂山的回应后,我以为我会添加一个链接到维基百科的策略模式文章,以供参考。感谢大家的回应!

解决方案

这是Java中非常标准的模式,也是实现Strategy模式的常用方式。你总是在标准API中看到它(Calendar与GregorianCalendar,NumberFormat和DecimalFormat等)。



据说,依赖注入是所有的愤怒,这样一个模式可能会被一个专用的Factory类替换为一个专用的Factory界面,但是在没有更大的设计原因的情况下,我认为你给出的例子是完全合理的设计选择。


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();
    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆