【问题标题】:Why use type substitution [closed]为什么使用类型替换
【发布时间】:2014-10-28 08:27:24
【问题描述】:

谁能向我解释一下使用类型替换的必要性是什么?

例如

class Circle extends Shape{
   ...
}

.
.
.

class Main{
   public static void main(String[] args){
       Shape s = new Circle();
       ...
   }
}

我们可以从上面的代码中得到什么好处?通常情况下,

public static void main(String[] args){
    Circle c = new Circle();
}

会轻松完成所需的工作。

【问题讨论】:

  • 问这种笼统的问题是离题的。
  • 因为真实的程序比这个玩具例子复杂得多。
  • @chrylis 是的,我现在可以从下面的答案(@adi)中看到:)
  • 如果您想要一个形状列表,则不需要。

标签: java oop types liskov-substitution-principle


【解决方案1】:

这种现象被称为通过继承的多态性。这意味着您的行为是在运行时决定调用哪个对象而不是调用哪个引用。

嗯。让我们进一步扩展您的示例。让我们首先创建类层次结构

class Shape{
      public void draw(){}
}

class Circle extends Shape{
      public void draw(){
          //mechanism to draw circle
      }
}

class Square extends Shape{
      public void draw(){
          //mechanism to draw square
      }
}

现在让我们看看这如何导致代码干净

class Canvas{
     public static void main(String[] args){
        List<Shape> shapes = new ArrayList<>();
        shapes.add(new Circle());
        shapes.add(new Square());

        // clean and neat code

        for(Shape shape : shapes){
              shape.draw();
        }

     }
 }

这也有助于建立松耦合系统

 Class ShapeDrawer{
     private Shape shape;  

     public void setShape(Shape shape){
         this.shape = shape;
     }

     public void paint(){
         shape.draw(); 
     } 

 }

在这种情况下,ShapeDrawer 与实际形状非常松散耦合。 ShapeDrawer 甚至不知道它正在绘制哪种类型的Shape,甚至不知道它是如何绘制的机制是从中抽象。可以改变绘制特定形状的底层机制而不影响这个类。

【讨论】:

  • 谢谢,帮助...
猜你喜欢
  • 2018-09-19
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 2018-10-07
  • 2021-02-19
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
相关资源
最近更新 更多