简体   繁体   English

Java:创建一个空接口以从一个属性访问不同的类?

[英]Java: Creating an empty interface to access different classes from one attribute?

I'm creating a FreeCell game, and at the end of the game I want it to print out the users moves. 我正在创建一个FreeCell游戏,在游戏结束时,我希望它可以打印出用户的动作。 So the solution is a Move[]. 因此解决方案是Move []。 The Move class looks like: Move类如下所示:

public class Move
{

   private Card card;
   private Location source;
   private Location target;

   public Move(Card card, Location source, Location target)
   {
      this.card = card;
      this.source = source;
      this.target = target;
   }
}

I want Location to be able to store the three different types of locations in a FreeCell game: The Cells (which can hold 1 card), the Cascades (which is where the cards are dealt), and the Foundations (where the cards are placed to solve the game). 我希望“位置”能够在FreeCell游戏中存储三种不同类型的位置:“单元”(可以容纳1张卡),“级联”(用于发卡的位置)和“基础”(用于放置卡的位置)解决游戏)。 So I need Location to be able to store objects of the Cell, Cascade, and Foundation classes. 因此,我需要Location才能存储Cell,Cascade和Foundation类的对象。 But these classes don't all have any attributes or methods that are shared between them, so a parent class doesn't make much sense. 但是这些类并不都具有在它们之间共享的任何属性或方法,因此父类没有多大意义。 Furthermore, Cascade already extends LinkedList to avoid warnings when creating an array of LinkedLists, and it can't extend two parent classes. 此外,Cascade已经扩展LinkedList以避免在创建LinkedList数组时出现警告,并且它不能扩展两个父类。

So is there an elegant solution to this? 那么,对此有一个优雅的解决方案吗? Should I create a blank interface called Location, or is there an easier aspect of OOP that I'm not thinking of that can be used here? 我应该创建一个名为Location的空白接口,还是OOP中我不认为可以在此处使用的更简单的方面?

Your Location s are just a small fixed set of values right: 您的Location只是一组小的固定值,对:
Cells 1 to 4 单元格1至4
Foundation 1 to 4 基础1至4
Cascade 1 to 8 级联1至8

You could use enum s. 您可以使用enum

public interface Location {}

public enum Cell implements Location { ONE, TWO, THREE, FOUR }

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

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