使几个类具有相同的属性,而无需继承



我在Java中面临问题。

我需要有几个具有相同属性的类(例如位置和布尔值可行)。

,但我不希望这些类从类元素继承,因为这会阻止我以后使用继承。

我想到了一个接口(以便接口具有属性),但是显然您不能从类中继承一个接口。

必须有一种方法,因为否则我必须复制/粘贴我的属性和方法。

预先感谢任何对如何克服这个问题有想法的人。

为此,我将考虑对继承的组成。

public class Main {
    public static void main(String[] args) {
        AgentWrapper agentWrapper = new AgentWrapper(new Agent1(), false, 1);
        System.out.println("isWalkable: " + agentWrapper.isWalkable());
        System.out.println("position: " + agentWrapper.getPosition());
        agentWrapper.getAgent().doSomething();
    }
}
interface Agent {
    void doSomething();
}
class Agent1 implements Agent {
    public void doSomething() {
        System.out.println("Agent1");
    }
}
class Agent2 implements Agent {
    public void doSomething() {
        System.out.println("Agent1");
    }
}
class AgentWrapper {
    private final Agent agent;  //Wrapped instance.
    private final boolean isWalkable;
    private final int position;
    public AgentWrapper(Agent agent, boolean isWalkable, int position) {
        this.agent = agent;
        this.isWalkable = isWalkable;
        this.position = position;
    }
    public Agent getAgent() {
        return agent;
    }
    public boolean isWalkable() {
        return isWalkable;
    }

我怀疑您可能需要一个接口,如果您想一般对象进行处理,例如循环绕着所有循环并绘制每个人。例如。假设您的元素包括"猫"one_answers"房屋":

interface Element{
   public point getPosition();
   public boolean isWalkable();
}
class Cat implements Element{
   private Point position;
   private String catBreed; // example of cat-specific data
   public point getPosition() {return position;}
   public boolean isWalkable() {return true;} // cats can walk
   ...
}
class House implements Element{
   private Point position;
   private String streetAddress; // example of house-specific data
   public point getPosition() {return position;}
   public boolean isWalkable() {return false;} // houses cannot walk  
   ..
}
// Finally, using that common interface:
Element[] allGameObjects= {new Cat(...), new Cat(...), new House(...) };
for(Element e:allGameObjects) 
   draw(e, e.getPosition());

对于我编写的几个系统来说,这已经足够好了,但是正如其他答复正确提到的,您可能会重构使用构图 - 但是它可能不是100%的清晰切割。我的意思是,我可以理解您是否觉得应该独立于他们的位置管理猫或房子...但是可行呢?

// Position is easy to separate:
class Cat { String catBreed; ... }
class House{ String streetAddress; ... }
class ElementWrapper implements Element{
   Point position;
   Object  theObject; // could hold Cat or House
   public Point getPosition() {return position;}
   // however, isWalkable is a bit tricky... see remark below
}

但'iSwalkable'是棘手的,因为在经典的多态性中,您希望House/Cat告诉您他们是否可以走路(这意味着他们应该实现界面)。如果您绝对不想要(或不能)拥有它,则可以在多态性上妥协并在实例中做某事(如果theObject是猫的实例,那么它可以走路,如果它是房屋的实例,它就无法行走,等等)。/p>

您可以扩展一个抽象的基类(一无所有),也可以按照评论中的建议使用装饰器模式,以获取与装饰图案有关的更多信息,您可以读取此链接。<<<<<<

最新更新