简体   繁体   English

类如何获取自身的实例?

[英]How can a class get an instance of itself?

Today, I was working on a tutorial with integrating buttons into a ground up built game engine. 今天,我正在编写将按钮集成到完全内置的游戏引擎中的教程。 This is the code that requests win. 这是要求获胜的代码。

public class ButtonEvent{

    private Window win;

    public ButtonEvent(){

        this.win = Window.getWindow();

    }

    /*Other methods*/

}

I watched the whole video through, but the guy who went over the class never mentioned what he did to his Window class to do this. 我看了整个视频,但是上课的那个人从来没有在Window课上提到他做了什么。 In that video he happened to click the window class and then click the next class and in that time, when I paused the video, I saw his getWindow() method. 在该视频中,他碰巧单击了窗口类,然后单击下一个类,并且在那段时间,当我暂停视频时,我看到了他的getWindow()方法。 Which I wrote below. 我在下面写的。

public class Window extends Canvas{

public Window win; //I tried doing this

    /*Other methods*/ 

    public static Window getWindow(){
        return win;
    }

}

Can someone explain to me how he does this? 有人可以向我解释他是如何做到的吗? I know the question is kind of vague, but it's all I have to work with. 我知道这个问题有点含糊,但是这就是我要做的全部工作。

Thanks! 谢谢!

Use the singleton pattern to ensure that only one instance of Window is created and used throughout the application. 使用单例模式可确保仅在整个应用程序中创建和使用一个Window实例。 Note that singletons are considered an "anti-pattern" meaning that there's usually a better way to go about it, such as using container-managed objects (see PicoContainer, Spring IoC, etc). 请注意,单例被认为是“反模式”,这意味着通常有更好的解决方法,例如使用容器管理的对象(请参阅PicoContainer,Spring IoC等)。

public class Window {
    private static Window INSTANCE = null;

    public static Window getWindow() {
        if (INSTANCE == null) {
            INSTANCE = new Window();
        }
        return INSTANCE;
    }
}

Change 更改

public Window win;

to

private static Window win = new Window();

And you will have the proper local visibility for getWindow() to see the Window field, and it will be initialized by calling the implicit empty constructor that the compiler inserts (that's the assignment of new Window ). 并且您将具有适当的局部可见性,以使getWindow()可以看到Window字段,并将通过调用编译器插入的隐式空构造函数(这是new Window的赋值)进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM