问题描述
我有一个'Character'类,Character是非静态的。我想让我的播放器类扩展字符,但也是静态的。
我基本上希望所有其他对象和类能够访问播放器,而无需创建和传递
最好的原因是什么?
我可以想到的唯一好的方法其实不是一个扩展而是一个包装器:
class Player {
private final static Charachter me = new Character();
public static doSomething(){me.doSomething(); }
}
当然你也可以扩展AND wrap:
class Player extends Character {
private final static Player me = new Player();
//如果你不想让任何人创建玩家对象
//使构造函数私有:
private Player(){super(); }
public void doSomething(){
// stuff
}
public static void staticDoSomething(){me.doSomething }
}
或者,实际上,因为你的目标只是为了保证单玩家对象,你可以忘记使方法静态,但隐藏构造函数:
private static Player thePlayer = null;
public static Player getPlayer(){
if(thePlayer == null){
//创建播放器
thePlayer = new Player
}
//有一个有效的player对象,所以返回它。
return thePlayer;
}
//通过将构造函数设为private来隐藏构造函数:
private Player(){super(); }
}
这样可以确保获得 Player
是调用 Player.getPlayer()
,它总是给你相同的对象(你永远不会创建多个)。
I have a class of 'Character', Character is non-static. I want my player class to extend Character but to also be static.
I basically want all other objects and classes to be able to access player without having to create and pass a player instance.
What's the best why to achieve this?
The only nice way I can think of is actually not an extension but a wrapper:
class Player {
private final static Charachter me = new Character();
public static doSomething(){ me.doSomething(); }
}
Of course you can also extend AND wrap:
class Player extends Character {
private final static Player me = new Player();
// if you don't want anyone creating player objects
// make the constructor private:
private Player(){ super(); }
public void doSomething(){
// stuff
}
public static void staticDoSomething(){ me.doSomething(); }
}
Or, actually, since your goal is just to guarantee that there is a single player object, you can forget about making the methods static, but hide the constructor(s):
class Player extends Character {
private static Player thePlayer = null;
public static Player getPlayer(){
if( thePlayer == null ){
// Create the player
thePlayer = new Player();
}
// There is a valid player object, so return it.
return thePlayer;
}
// hide the constructor(s) by making them private:
private Player(){ super(); }
}
That ensures that the only way to get a Player
is to call Player.getPlayer()
, and that it always gives you the same object (you never create more than one).
这篇关于Java - 非静态类的扩展静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!