简体   繁体   中英

How can i instantiate a different subclass based on common identifier (java)

I have a class for a tile.

public abstract class Tile {
    public Position pos;
    public char chr;
}

And many different classes that extend tile. Each subclass has its own identifier char. Now I have a function that receives a char and a position and needs to create and return a new instance of a tile subclass fitting the char in given position. Is there an elegant OOP way to do this other than run through all of the options?

So for me use of an identifier like this is a bit of a design flaw.

You could add something like the following to the abstract class:

public static Tile factory(char identifier, Position p) {
   Tile value = null;
   switch (identifier) {
      case `x`: {
        value = new XTile(p);
        break;
      }
      default {
        // throw an exception or provide a default
      }
   }
   return value
}

Effective Java (third edition) Item 21 "Prefer Class hierarchies to tagged classes" might provide an alternative to your design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM