dimanche 21 mars 2021

Is it conventional to write a singleton that contains the class it is Instantiate?

Is it customary to write a singleton containing the class from which it creates an object and in addition this class contains a private constructor so that it is not possible to create another object from this class by the 'new' keyword?

package com.isi.core;

import com.isi.handlers.MouseMotionHandler;
import com.isi.states.MainMenuState;
import com.isi.states.PlayState;
import com.isi.uicomponents.Button;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Singleton {

    private static MouseHandler instance = null;

    public static MouseHandler getInstance(Game game) {
        if (instance == null)
            instance = new MouseHandler(game);
        return instance;
    }

    public static class MouseHandler extends MouseAdapter {

        private Game game;

        private MouseHandler(Game game) {
            this.game = game;
        }

        public void mousePressed(MouseEvent e) {
            MouseMotionHandler mouseMotionHandler = game.getMouseMotionHandler();

            if (mouseMotionHandler.getOnComponent() != null && e.getButton() == 1 && mouseMotionHandler.getOnComponent() instanceof Button) {
                Button button = (Button) mouseMotionHandler.getOnComponent();

                if (game.getState() instanceof MainMenuState) {
                    if (button.getText().getString().equals("Play")) {
                        game.getGameStateManager().push(new PlayState(game));
                    } else if (button.getText().getString().equals("Exit")) {
                        System.exit(0);
                    }
                }
            }
        }

        public void mouseReleased(MouseEvent e) {

        }
    }
}

I created a singleton class that returns a single MouseHandler created from a private MouseHandler constructor.

Aucun commentaire:

Enregistrer un commentaire