我正在编写一些小型、简单的应用程序,它们共享一个共同的结构,并且需要以相同的方式做一些相同的事情(例如日志记录、数据库连接设置、环境设置),我正在寻找一些关于构建可重复使用的组件。代码是用强类型和静态类型的语言编写的(例如 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 块中......