多个实例与单个静态实例
假设我有这个自定义组件。它是 JMenuItem
的子类,并且所有实例都使用相同的 Font
对象,尽管没有一个实例共享相同的实例。例如,
public abstract class JFooMenuItem extends JMenuItem{
public JFooMenuItem(final String title){
super(title);
setFont(new Font("Courier New", Font.BOLD, 12));
}
}
现在,考虑到可能有多达 10 个以上的菜单项,将 Font
实例设置为共享的 static
成员变量会更有效吗?当前的设置(即上面的代码)很好(内存管理方面)?
Let's say I have this custom component. It subclasses JMenuItem
and all instances use the same Font
object, although none share the same instance. For example,
public abstract class JFooMenuItem extends JMenuItem{
public JFooMenuItem(final String title){
super(title);
setFont(new Font("Courier New", Font.BOLD, 12));
}
}
Now, given that there may be up to 10+ menu items, would it be more efficient to make the Font
instance a shared, static
member variable, or is this current setup (i.e. the code above) just fine (memory-management-wise)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会说使用一个命名实例,不是因为内存,而是因为如果您决定更改字体,则必须在
10+
位置进行编辑。public static final Font MENU_FONT = new Font("Courier New", Font.BOLD, 12);
编辑:即使您使用子类化,最好将其声明为
public static final
因为Font
是不变的。更清楚了。I would say use one named instance, not because of the memory, but because if you decide to change the font, you have to edit at
10+
places.public static final Font MENU_FONT = new Font("Courier New", Font.BOLD, 12);
Edit: Even if you use subclassing, better declare it as
public static final
because theFont
is constant. It is more clear.我相信与 10 个
Font
实例相关的内存开销并不是这里真正关心的问题。但是,从代码风格来看,您的Font
是该类型的所有实例中的常量,因此我认为如果以这种方式处理,您的代码将更具可读性。I believe the memory overhead associated with the 10 instance of
Font
to not be an issue of real concern here. However, from a code style, yourFont
is a constant across all instances of this type, therefore I think your code would be more readable if it were treated that way.每次实例化
JFooMenuItem
时,您的代码都会构造一个新的Font
对象。如果将其设为静态成员,则
Font
仅分配一次。You code will construct a new
Font
object every time you instantiate aJFooMenuItem
.If you make it a static member, the
Font
is only allocated once.