模型从卡特彼勒到蝴蝶在Java

我最近在接受采访时被问到这个问题:

Model animals that change their behaviour over time.

  1. Can you model a butterfly?

    • A butterfly can fly * A butterfly does not make a sound
  2. Can you optimize your model to account for the metamorphosis from caterpillar to butterfly?

    • A caterpillar cannot fly
    • A caterpillar can walk (crawl)

我创建了一个带有顶级接口(Insect)的层次结构,它有2个接口扩展它(GroundInsect& FlyingInsect).然后我让卡特彼勒实施GroundInsect和ButterFly实施FlyingInsect.但是,我无法为变态部分提出解决方案.以下是我的代码:

昆虫界面:

public interface Insect { }

FlyingInsect接口:

public interface FlyingInsect extends Insect {
    public boolean fly();
}

GroundInsect接口:

public interface GroundInsect extends Insect {
    // Walk/Crawl
    public boolean walk();
}

卡特彼勒类:

public class Caterpillar implements GroundInsect {

    @Override
    public boolean walk()
    {
        System.out.println("Caterpillar Walk method");
        return true;
    }
}

ButterFly类:

public class Butterfly implements FlyingInsect {

    @Override
    public boolean fly() {
        System.out.println("ButterFly Flying method");
        return false;
    }
}

最佳答案 让我们保持简单的示例并坚持您的初始方法.

首先,我将介绍描述各种昆虫的通用界面:

interface Insect {
    boolean fly();
    boolean walk();
    boolean sound();
}

方法fly,walk,sound表示昆虫与其邻域之间可能的相互作用(取决于这些相互作用的性质,方法可能不同且更复杂:返回复杂的响应,接受回调等).

你的第一个蝴蝶只是界面的一些具体实现:

class Butterfly implements Insect {
    boolean fly() { return true; }
    boolean walk() { return true; }
    boolean sound() { return false; }
}

现在让我们添加转换的能力.同样,通常有各种方法可以做到这一点,所以让我们坚持蝴蝶的例子.

让我们说我们想要一只毛毛虫和它相关的蝴蝶是一个单一的实体(我们不希望当蝴蝶已经在那里时毛毛虫仍然四处游荡).

在这种情况下,我将毛虫和蝴蝶表示为一个单独的类并隐藏它的当前状态. “caterpillar状态”和“蝴蝶状态”都将包含在转换后应该更改的不同操作实现.封闭实例会将其方法委托给当前状态.

class Butterfly implements Insect {

    private Insect state = new CaterpillarState();

    boolean fly() { return state.fly(); }
    boolean walk() { return state.walk(); }
    boolean sound() { return state.sound(); }

    void transform() { state = new ButterflyState(); }

    private class ButterflyState implements Insect {
        boolean fly() { return true; }
        boolean walk() { return true; }
        boolean sound() { return false; } 
    }

    private class CaterpillarState implements Insect {
        boolean fly() { return false; }
        boolean walk() { return true; }
        boolean sound() { return true; }             
    }
}

变换方法代表了变态的触发器.

这里ButterflyState和CaterpillarState实现与外部类相同的Insect接口.在一般情况下,我可能会为内部状态定义不同的接口.

点赞