【问题标题】:Dependency Inversion principle breaks when interface implementation has more methods than the interface?当接口实现的方法比接口多时,依赖倒置原则会失效?
【发布时间】:2018-04-28 01:30:05
【问题描述】:

我想知道如何在不破坏依赖倒置原则的情况下调用类中的方法?

在下面的示例中,如果我有一个名为 Animal 的接口,例如:

interface Animal {
     void walk();
}

而且,它的实现如下:

public class Bird implements Animal{
     public void walk() {
          //Do Something
     }

     public void fly() {
         //Do Something
     }
}

我想执行fly()方法,我的代码目前看起来是这样的,它打破了依赖倒置原则。

public class Start {

  private Bird bird;

  @inject
  public Start(Bird bird) {
     this.bird = bird;
     this.bird.fly();     // THIS BREAKS DEPENDENCY INVERSION
  }

}

如果不在界面中添加fly() 或为Birds 创建新界面,我如何才能做到这一点?

【问题讨论】:

  • 调用fly 方法不会破坏依赖倒置。它通过存储变量private Bird 被破坏。 Bird 是一个具体的类;根据 DIP,具体类不能是成员变量或字段。

标签: java solid-principles


【解决方案1】:

怎么样:

interface IMovable {
    void move(int distance);
}

实施:

public class Bird implements IMovable {
    @override
    public void move(int distance) {
        if(distance > 5) {
            walk();
        } else {
            fly();
        }
    }

    public void walk() {
         //Do Something
    }

    public void fly() {
        //Do Something
    }
}

用法:

public class Start {

    private IMovable animal;

    @inject
    public Start(IMovable animal) {
       this.animal = animal;
       this.animal.move(100);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多