我有这样的代码:
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中是 Not Acceptable 。如何解决呢?谢谢。 我尝试用init方法替换它,但不知道如何继续。
最佳答案
对。它不是单例
。这是一个Multiton
它扩展了单例概念,以将命名实例映射作为键值对进行管理。
关于 java 。带参数的 Singleton 和 getInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700126/