什么时候使用继承? [英] When to use inheritance?

查看:218
本文介绍了什么时候使用继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的朋友进行了一些辩论。
我必须实现一个浏览器进程监视器类,只要正在监视的浏览器(比如说Internet Explorer)正在运行,就会调用一个事件。

Me and my friend had a little debate. I had to implement a "browser process watcher" class which invokes an event whenever the browser that is being watched (let's say Internet explorer) is running.

我们创建了一个进程观察者类,这里开始辩论:

We created a "Process watcher" class, and here starts the debate:

他说构造函数应该只接受字符串(比如iexplore.exe),而我我们应该继承进程观察者来创建一个浏览器观察者,它接受当前使用的浏览器枚举,构造函数将其翻译为iexplore。
他说我们应该使用一个函数函数来充当翻译器。

He said that the constructor should only accept strings (like "iexplore.exe"), and i said we should inherit "Process watcher" to create a "browser watcher" which accepts the currently used browser enum, which the constructor will "translate" it to "iexplore". he said we should use a util function which will act as the translator.

我知道这两种方式都是有效的,但我不知道有什么方法和每种情况的缺点,以及在我们的情况下适合的情况。

I know both ways are valid and good, but i wonder whats the pros and cons of each, and what is suitable in our case.

推荐答案

最近我采取了保持简单的方法现在,如果你需要扩展它,可以稍后进行重构。

Lately I've been taking the approach of "Keep it simple now, and refactor later if you need to extend it".

你现在正在做的事情看起来很简单。你真的只有一个你想要处理的案例。所以我现在说采取更简单的方法。最后,如果你永远不需要制作另一种观察者,那么你将避免额外的复杂性。但是,如果需要,可以在以后重新编码的方式对其进行编码。

What you're doing right now seems pretty simple. You only really have one case that you're trying to handle. So I'd say take the simpler approach for now. In the end, if you never have to make another kind of watcher then you'll avoid the extra complexity. However, code it in a way that will make it easier to refactor later if you need to.

将来,如果您发现需要其他类型的观察者,请花费然后努力将其重构为继承(或组合,或您想要遵循的任何其他模式)。如果您的初始代码完成正确,重构应该相当容易,因此您并没有真正添加额外的工作。

In the future, if you find you need another type of watcher, spend the effort then to refactor it into an inheritance (or composition, or whatever other pattern you want to follow). If your initial code is done right the refactoring should be fairly easy, so you're not really adding much extra work.

我发现这种方法效果相当好我。在我真的不需要继承的情况下,代码保持简单。但是当我确实需要它时,我可以添加它而没有任何实际问题。

I've found this approach works fairly well for me. In the cases where I really didn't need inheritance the code stays simple. But when I really do need it I can add it in without any real problems.

这篇关于什么时候使用继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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