我遇到过几次的一件事是服务类(如 JBoss 服务)由于辅助内部类而变得过大。我还没有找到打破课堂的好方法。这些助手通常是线程。这是一个例子:
/** Asset service keeps track of the metadata about assets that live on other
* systems. Complications include the fact the assets have a lifecycle and their
* physical representation lives on other systems that have to be polled to find
* out if the Asset is still there. */
public class AssetService
{
//...various private variables
//...various methods
public AssetService()
{
Job pollerJob = jobService.schedule( new AssetPoller() );
Job lifeCycleJob = jobService.schedule( AssetLifecycleMonitor() );
}
class AssetPoller
{
public void run()
{
// contact remote systems and update this service's private variables that
// track the assets.
}
}
class AssetLifecycleMonitor
{
public void run()
{
// look for assets that have meet criteria for a lifecycle shift
// and update this service's private variables as relevant.
}
}
}
所以,如果我有几个助手并且它们很复杂,会发生什么,整个类文件会变得非常大。我喜欢内部类,因为它清楚地表明这些类完全归服务所有,并且只为帮助该服务而存在。我试过打破类并将父服务作为参考传递,这主要是有效的,但我不喜欢的事情是:
So, in short, breaking the classes out loses some of the encapsulation I like. But leaving them in can lead to some large java files. I've yet to find a good way to deal with this. C++ had the concept of "friends" which I've rarely missed, but would actually help in this case.
Thoughts?