简体   繁体   English

Java的。 抽象元素列表。 如何确定元素类型

[英]Java. Abstract elements list. How to determine element type

I have basic abstract class: 我有基本的抽象类:

 abstract class Graphic 
 {
 abstract void draw(Graphics g);
 }

I have Group class which helps to group elements into particular groups. 我有Group类,它有助于将元素分为特定的组。 Notice that this Group class can have other Group elements inside itself. 注意,该Group类可以在其内部包含其他Group元素。

 class Group extends Graphic
 {
     private ArrayList<Graphic> children = new ArrayList<Graphic>();
 public ArrayList<Graphic> getChildren() 
 {
      return children;
 }

 public void setChildren(ArrayList<Graphic> children) 
 {
          this.children = children;
 }

 public void draw(Graphics g)
 {
     for(Graphic child:children)
     {
          child.draw(g);
     }
 }
 }

Here is the line class which also extends Graphic. 这是线类,它也扩展了Graphic。

 class Line extends Graphic  {
     private Point startPoint = new Point(0,0);
 private Point endPoint = new Point(1,1);

 public void draw(Graphics g) 
 {
     g.drawLine(startPoint.x, startPoint.y, endPoint.x, cendPoint.y);
 }
 }

I can add Line element or another Group element into Group class children list, that is I can group the groups and these groups can have their own groups too and every group can have line element too, however I'm unable to determine whether the child element is Group or Line. 我可以将Line元素或另一个Group元素添加到Group类的子级列表中,也就是说,我可以对这些组进行分组,这些组也可以拥有自己的组,每个组也可以具有line元素,但是我无法确定该子级是否元素是组或线。 How can I determine whether the element is Group or Line? 如何确定元素是“组”还是“线”?

instanceof operator or compare object.getClass() object. instanceof运算符或比较object.getClass()对象。 But checking concrete type of object is not good practice. 但是检查对象的具体类型不是一个好习惯。 You should depend only on public interface (your Graphic ) 您应该仅依靠公共界面(您的Graphic

Use instanceof or reflection: 使用instanceof或反射:

public void draw(Graphics g) 
{
   for(Graphic child:children)
   {
      child.draw(g);

      if (child instanceof Line) {
         System.out.println("child is of type Line");
      }

      System.out.printf("child is of type %s%n", child.getClass());
   }
 }

But you should not need it except for debugging. 但是除了调试外,您不需要它。 If you do you better check your design again. 如果您这样做,则最好再次检查您的设计。

Few more things: 几件事:

  • Do not use ArrayList except to specify implementation, use List instead (this allows switching implementation say to LinkedList by changing a single line) 不要使用ArrayList来指定实现,而要使用List代替(这允许通过更改一行将实现切换到LinkedList
  • If Graphics provides no implementation, use interface instead of an abstract class (a class can inherit only one class, but it can implement multiple interfaces) 如果Graphics提供任何实现,请使用接口代替抽象类(一个类只能继承一个类,但可以实现多个接口)

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

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