lambda 表达式可以替代多态性吗?Java 中 lambda 表达式的优点。
我正在学习lambda表达式和函数接口。我们可以通过 lambda 表达式直接编写接口的实现。所以我认为,它可能是多态性的替代方案。
我有一些使用多态性的代码,
interface Drawable {
public void draw();
}
class Shape {
protected String name;
public Shape(String name) {
this.name = name;
}
}
class Rectangle extends Shape implements Drawable {
public Rectangle(String name) {
super(name);
}
@Override
public void draw() {
System.out.println("I am "+this.name);
System.out.println("Drawing rectangle with 2 equal sides.");
}
}
class Square extends Shape implements Drawable {
public Square(String name) {
super(name);
}
@Override
public void draw() {
System.out.println("I am "+this.name);
System.out.println("Drawing square with 4 equal sides.");
}
}
public class DrawShape {
public static void main(String ar[]) {
Drawable rectangle = new Rectangle("Rectangle");
rectangle.draw();
Drawable square = new Square("Square");
square.draw();
}
}
我已经使用lambda表达式和函数接口编写了上面的代码,
@FunctionalInterface
interface Drawable {
public void draw();
}
class Shape {
private String name;
public Shape(String name) {
this.name = name;
}
public void draw(Drawable d1) {
System.out.println("I am "+this.name);
d1.draw();
}
}
public class DrawShape {
public static void main(String[] args) {
Shape s1 = new Shape("Rectangle");
Drawable rectangle = () -> System.out.println("Drawing rectangle with 2 equal sides.");
s1.draw(rectangle);
Shape s2 = new Shape("Square");
Drawable sqaure = () -> System.out.println("Drawing square with 4 equal sides.");
s2.draw(sqaure);
}
}
哪种方法更好?lambda的其他方面,如代码可重用性,代码维护和修改,耦合和内聚等呢?