我正在编写一些小型、简单的应用程序,它们共享一个共同的结构,并且需要以相同的方式做一些相同的事情(例如日志记录、数据库连接设置、环境设置),并且我正在寻找一些构建这些应用程序的建议可重复使用的组件。该代码是用强静态类型语言编写的(例如 Java 或 C#,我必须用这两种语言来解决这个问题)。目前我得到了这个:
abstract class EmptyApp //this is the reusable bit
{
//various useful fields: loggers, db connections
abstract function body()
function run()
{
//do setup
this.body()
//do cleanup
}
}
class theApp extends EmptyApp //this is a given app
{
function body()
{
//do stuff using some fields from EmptyApp
}
function main()
{
theApp app = new theApp()
app.run()
}
}
有没有更好的办法?也许如下?我很难权衡利弊...
abstract class EmptyApp
{
//various fields
}
class ReusableBits
{
static function doSetup(EmptyApp theApp)
static function doCleanup(EmptyApp theApp)
}
class theApp extends EmptyApp
{
function main()
{
ReusableBits.doSetup(this);
//do stuff using some fields from EmptyApp
ReusableBits.doCleanup(this);
}
}
一个明显的权衡是,使用选项 2,“框架”无法将应用程序包装在 try-catch 块中......
我一直赞成通过组合(您的第二个选择)而不是继承(您的第一个选择)来重用。
仅当类之间存在关系时才应使用继承,而不是为了代码重用。
因此,对于您的示例,我将有多个 ReusableBits 类,每个类执行每个应用程序在需要时使用的一件事。
这允许每个应用程序重复使用与该特定应用程序相关的框架部分,而不必被迫采用所有内容,从而允许各个应用程序更加自由。如果您将来的某些应用程序不完全适合您今天所考虑的结构,那么通过继承进行重用有时会变得非常具有限制性。
如果您将框架分解为单独的实用程序,您还会发现单元测试和测试驱动开发变得更加容易。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)