下面,我们来看一个demo。假设,长方形是正方形的基类,长方形有一个方法叫做resize(),这个方法的作用是如果宽度小于长度,就重新调整大小,使宽度大于长度一个单位。正方形也可以调用这个方法,但是却改变了自己是正方形的事实。这就违背了程序行为没有变化这一条件。
package liskovsubstitution
type QuardRangle interface {
Width() int
Length() int
}
package liskovsubstitution
type Rectangle struct {
length int
width int
}
func (r *Rectangle) SetWidth(width int) {
r.width = width
}
func (r Rectangle) SetLength(length int) {
r.length = length
}
func (r Rectangle) Width() int {
return r.width
}
func (r Rectangle) Length() int {
return r.length
}
package liskovsubstitution
type Square struct {
sideLength int
}
func NewSquare(sideLength int) *Square {
return &Square{sideLength: sideLength}
}
func (s *Square) SetSideLength(sideLength int) {
s.sideLength = sideLength
}
func (s Square) Width() int {
return s.sideLength
}
func (s Square) Length() int {
return s.sideLength
}
package liskovsubstitution
import (
"fmt"
"testing"
)
func Test(t *testing.T) {
square := NewSquare(10)
//resize(square)
}
func resize(rectangle Rectangle) {
for rectangle.Width() <= rectangle.Length() {
rectangle.SetWidth(rectangle.Width() + 1)
fmt.Printf("width:%d,length:%d", rectangle.Width(), rectangle.Length())
}
}
package tech.selinux.design.principle.liskovsubstitution;
public interface Quadrangle {
long getWidth();
long getLength();
}
package tech.selinux.design.principle.liskovsubstitution;
public class Rectangle implements Quadrangle {
private long length;
private long width;
@Override
public long getWidth() {
return width;
}
@Override
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public void setWidth(long width) {
this.width = width;
}
}
package tech.selinux.design.principle.liskovsubstitution;
public class Square implements Quadrangle {
private long sideLength;
public long getSideLength() {
return sideLength;
}
public void setSideLength(long sideLength) {
this.sideLength = sideLength;
}
@Override
public long getWidth() {
return sideLength;
}
@Override
public long getLength() {
return sideLength;
}
}
package tech.selinux.design.principle.liskovsubstitution;
public class Test {
public static void resize(Rectangle rectangle){
while (rectangle.getWidth() <= rectangle.getLength()){
rectangle.setWidth(rectangle.getWidth()+1);
System.out.println("width:"+rectangle.getWidth() + " length:"+rectangle.getLength());
}
System.out.println("resize方法结束 width:"+rectangle.getWidth() + " length:"+rectangle.getLength());
}
// public static void main(String[] args) {
// Rectangle rectangle = new Rectangle();
// rectangle.setWidth(10);
// rectangle.setLength(20);
// resize(rectangle);
// }
public static void main(String[] args) {
Square square = new Square();
// square.setLength(10);
// resize(square);
}
}
补充另一个版本的Java/Scala Demo 以及源码解析