Tap*_*ose 3 java concurrency singleton swing event-dispatching
我正在开发一个swing应用程序,我在其中有一个Factory类,它提供了组件,同时考虑了Singleton.喜欢:
public final class ComponentFactory {
private static LibraryFrame libraryFrame;
private static LibraryTableScrollPane libraryTableScrollPane;
public static synchronized LibraryFrame getLibraryFrame() {
if (libraryFrame == null) {
libraryFrame = new LibraryFrame();
}
return libraryFrame;
}
public static synchronized LibraryTableScrollPane getLibraryTableScrollPane() {
if(libraryTableScrollPane == null) {
libraryTableScrollPane = new LibraryTableScrollPane(getLibraryTable());
}
return libraryTableScrollPane;
}
}
Run Code Online (Sandbox Code Playgroud)
我使用这个组件:
add(ComponentFactory.getLibraryTableScrollPane())
Run Code Online (Sandbox Code Playgroud)
我还创建了一个ListenerFactory类,它提供了各种Swing/AWT监听器.
这种模式有什么缺陷吗?我可以使用具有两个同时可见的父组件的相同组件或侦听器吗?
提前致谢.
它有一个重大缺陷:它通过使每个组件在全球范围内可访问来促进缺乏封装.这可以非常快速地导致意大利面条代码,其中每个对象使用任何其他对象,而不是具有提供封装方法的简短依赖关系列表.
另一个问题是实现:同步是不必要的,因为Swing组件不是线程安全的,并且可能只能从事件派发线程使用.因此,您应该只让EDT调用您的方法,这样就不需要进行同步.
最后,组件可能只有一个父组件.例如,如果相同的组件必须显示在两个不同的帧中,则需要此组件的两个实例.