简体   繁体   English

我如何根据公共标识符(java)实例化不同的子类

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

I have a class for a tile.我有一个用于瓷砖的 class。

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

And many different classes that extend tile.以及许多扩展 tile 的不同类。 Each subclass has its own identifier char.每个子类都有自己的标识符 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.现在我有一个 function 接收一个字符和一个 position 并且需要创建并返回一个瓷砖子类的新实例,该实例适合给定 position 中的字符。 Is there an elegant OOP way to do this other than run through all of the options?除了运行所有选项之外,是否有一种优雅的 OOP 方法可以做到这一点?

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:您可以在抽象 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.有效的 Java(第三版)第 21 项“首选 Class 层次结构而不是标记类”可能会为您的设计提供替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据标识符实例化某个子类,还是有更好的方法? - How to instantiate a certain subclass depending on an identifier, or is there a better way? 我可以实例化一个超类并根据提供的参数实例化一个特定的子类吗 - Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied 如何根据按下的按钮实例化不同大小的图标java - how to instantiate different size icons based on the button pressed java 如何使用 JNI 实例化 Java 泛型? - How can I instantiate a Java generic with JNI? 如何在Java中实例化泛型类型? - How can I instantiate a generic type in Java? 我如何从另一个包中实例化Java内部的public static final类 - How can I instantiate a inner public static final class in java from a different package 在Java中,我可以使子类的实例“基于”超类的实例吗? - In Java, can I make an instance of a subclass “based on” an instance of the superclass? 如何使用推土机实例化子类? - How to instantiate a subclass with Dozer? 如何在不同情况下使用不同的子类? - How can I use different subclass in different situation? 如何实例化在Java中实现Java接口的JRuby类 - How can I instantiate a JRuby class that implements a Java interface in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM