Java的。带参数的Singleton和getInstance

时间:2016-01-09 23:22:54

标签: java singleton

我有这样的代码:

public class Hero extends Costam {

    private static Hero heroInstance;

    Weapon weapon;
    static Image idleImg = new ImageIcon("idle.png").getImage();
    static Image movingImg = new ImageIcon("moving.png").getImage();
    static Image fallingImg = new ImageIcon("falling.png").getImage();
    static Image jumpingImg = new ImageIcon("jumping.png").getImage();

    private LinkedList<Sprite> sprajty;
    private ArrayList<Segment> plansza;

    static int[] idleArray = new int[]{0, 1, 1, 2, 2, 3}, movingArray = new int[]{0, 1, 2, 3, 4, 5},
            fallingArray = new int[]{0}, jumpingArray = new int[]{0, 1, 2};

    static ArrayList<Image> obrazy = new ArrayList<Image>() {
        {
            add(idleImg);
            add(movingImg);
            add(fallingImg);
            add(jumpingImg);

        }
    };

    static ArrayList<int[]> tablice = new ArrayList<int[]>() {
        {
            add(idleArray);
            add(movingArray);
            add(fallingArray);
            add(jumpingArray);

        }
    };

    private Hero(ArrayList<Segment> plansza, LinkedList<Sprite> sprajty) {
        super(new Sprite(plansza, obrazy, tablice));
        this.plansza = plansza;
        weapon = new BasicWeapon(new ImageIcon("blue-portal.png").getImage());
        this.sprajty = sprajty;

        velocityX = 8;
    }

    //SINGLETON - ten get instance btw
    public Hero getInstance ()
    {
        if (heroInstance == null)
        {
            heroInstance = new Hero(plansza, sprajty);
        }
        return heroInstance;
    }

    public static Hero getInstance (ArrayList<Segment> plansza, LinkedList<Sprite> sprajty)
    {
        if (heroInstance == null) {
            heroInstance = new Hero(plansza,sprajty);
        }
        return heroInstance;
    }

正如您所看到的,有一个带参数的getInstance方法,这在Singleton中是不可接受的。怎么解决?谢谢。 我尝试用init方法替换它,但不知道如何继续它。

1 个答案:

答案 0 :(得分:1)

右。它不是Singleton。这是一个Multiton 扩展了单例概念,将命名实例的地图作为键值对进行管理。