Java - Extended static class of a non-static class

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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?

回答1:

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).



回答2:

Really it seems like you just want a global variable. This is often accomplished through the Singleton pattern:

public class Player extends Character {     private static final Player humanPlayer = new Player();      private Player() {     }      public static Player getHuman() {         return humanPlayer;     }      //... }  //... Player.getHuman().move(2); 

There should be very little need for those methods in Player to be static. You're sacrificing good design for a tiny bit of convenience (that will probably bite you later anyway).

Personally I favour dependency injection over global state about 95% of the time. When a method needs to have access to the player, pass it in. That will let you test your code much more easily and will make your code more conducive to change.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!