2012-11-28 61 views
0

我正在研究GUI应用程序(简单游戏),其中一个对象(让我们称之为对象A)使用直接加载的图像。我正在实现在游戏开始时加载图像的方法,以便我不必每次重新配置游戏时都要重新加载文件等。该方法将所有必需图像作为数组加载,然后使用另一种方法(BufferedImage[] getImages());返回这个数组。该方法的类(对象B,JPanel)绘制对象A,而对象A又由对象C(JFrame,当然,它也实例化对象B)实例化。使用另一个类的对象而不将它传递给构造函数

我想知道我是否可以直接从对象A的方法访问对象B的getImages()方法,而无需通过方法调用传递参考。是完全可能的(通过ClassPath等),这是否是一个很好的编程习惯?

回答

0

这听起来像你正在寻找单身模式。这样做:

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而不是数组,使其更容易知道在你的代码返回什么形象。


顺便说一句,你可以阅读the different reasons when you would and would not use a static method here.

+1

@theUg:依赖注入在您需要时非常美妙(例如,数据源的潜在更改)......在项目的生活方式中尽早构建是件好事,因为重构非常困难......但完全不需要作业:) – durron597

0

一个很好的讨论,您可以拨打B的getImages()方法,而不必仅在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; 
    } 
} 

但是请注意,这是单身经一些人皱起了眉头。 替代方案是dependency injection

+0

令人惊讶的是你的代码与我的相似程度如何) – durron597

+0

那么,静态方法和单例类(为了我的应用程序的目的)是否会做同样的事情,因为它也会产生单个对象呢?考虑到单身人士的担忧,或者你对静态方法如何可能或不可能是一个好主意的警告,那么更好的方法是什么? – theUg

+0

@theUg:我编辑了一个关于静态和单身的好链接,并将其写入我的回答上面 – durron597

相关问题