[英]Using object of another class without passing it to a constructor
我正在使用GUI应用程序(简单游戏),其中一个对象(让我们称之为对象A)使用我直接加载的图像。 我正在实现在游戏开始时加载图像的方法,这样就不必在每次重新配置游戏等时都重新加载文件。该方法将所有必需的图像加载为数组,然后加载另一个方法( BufferedImage[] getImages()
); 返回此数组。 此方法的类(对象B,JPanel)绘制对象A,而对象A又由对象C实例化(JFrame,当然也实例化对象B)。
我想知道是否可以直接从对象A的方法访问对象B的getImages()
方法,而无需通过方法调用传递引用。 是否完全有可能(通过ClassPath等),这样做是否是一种好的编程习惯?
听起来您正在寻找单例模式。 做这个:
public class ImageContainer {
private final BufferedImage[] images = null;
private static ImageContainer _instance = new ImageContainer();
// NOTE PRIVATE CONSTRUCTOR
private ImageContainer() {
BufferedImage[] images = loadImages();
}
public static ImageContainer getInstance() {
return _instance;
}
private BufferedImage[] loadImages() {
// Do the loading image logic
}
// You might not want this in favor of the next method, so clients don't have direct access to your array
public BufferedImage[] getImages() {
return images;
}
public BufferedImage getImage(int index) {
return BufferedImage[i];
}
}
然后,只要您需要图像,就要做
ImageContainer.getInstance().getImage(3);
您甚至可以使用EnumMap
而不是数组来更轻松地知道要在代码中返回的图像。
顺便说一句,您可以在这里阅读关于是否使用静态方法的各种原因的精彩讨论。
仅当getImages是静态方法时,才可以在没有引用的情况下调用B的getImages()方法。 根据您的情况,这可能不是一个好主意。
另一种选择是使B成为“单个”类。 您可以像这样大致完成:
public class B {
private static B theInstance;
private bufferedImage[] images;
private B() {
}
public static B getInstance() {
if(theInstance == null) {
theInstance = new B();
}
return theInstance;
}
public BufferedImage[] getImages() {
if(images == null) {
/* get the images */
}
return images;
}
}
但是请注意,某些人不赞成单身人士。 另一种方法是依赖注入 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.