里氏替换原理 - 重写方法示例

发布于 2024-12-22 08:56:20 字数 596 浏览 3 评论 0原文

假设我们有一个非常简单的类:

class A
{
    virtual int Function(int number)
    {
      return number;
    }
}

class B : A
{
    override int Function(int number)
    {
        return number + 1;
    }
}

class UseExample
{
    void Foo(A obj)
    {
        A.Function(1);
    }
}

这个例子会违反 LSP 吗?如果是这样,你能给我一个不违反原则并使用不同实现的例子吗?

这个怎么样:

class B : A
{
    int variable;

    override int Function(int number)
    {
        return number + variable;
    }
}

据我了解,变量 "variable" 的使用会导致更强的前提条件,因此违反了 LSP。但我不完全确定在使用多态性时如何遵循 LSP。

Lets say we have this really trivial classes:

class A
{
    virtual int Function(int number)
    {
      return number;
    }
}

class B : A
{
    override int Function(int number)
    {
        return number + 1;
    }
}

class UseExample
{
    void Foo(A obj)
    {
        A.Function(1);
    }
}

Would be this example a violation of the LSP?. If so, could you give me an example that does not break the principle and uses a different implementation?

What about this one:

class B : A
{
    int variable;

    override int Function(int number)
    {
        return number + variable;
    }
}

As far as I understood the use of the variable "variable" causes a stronger pre-condition and therefore it violates the LSP. But i'm not completely sure how to follow the LSP when using Polymorphism.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪意 2024-12-29 08:56:20

这是有效的,在这两种情况下都没有违反原则。 B可以代替A。只是功能不同。

打破契约的一个简单方法是,如果数字 == 23 或其他什么,则在 Bs override 中抛出异常:)

That's valid, in both cases it doesn't break the principle. B can be substituted for A. It just has different functionality.

a simple way to break the contract would be to throw an exception in Bs override if the number == 23 or something :)

橘味果▽酱 2024-12-29 08:56:20

根据我的理解,我想说你的两个例子都违反了 LSP,因为子类不能被它的超类替换。
请考虑以下情况:

class UseExample {
    void Foo(A& obj, int number) {
        int retNumber = obj.Function(number);
        assert(retNumber==number);
    }
}

如果要将 B 对象的引用传递给 Foo,则断言将失败。 B.Function 正在改变 A.Function 的后置条件。
Foo 客户端代码不必知道可能会破坏其代码的子类型。

From my understanding of it I would say that both your examples violate LSP as the subclass cannot be replaced by its superclass.
Consider the following:

class UseExample {
    void Foo(A& obj, int number) {
        int retNumber = obj.Function(number);
        assert(retNumber==number);
    }
}

If you were to pass a reference to a B object into Foo the assert will fail. The B.Function is changing the poscondition of A.Function.
The Foo client code shouldn't have to know about possible subtypes which may break their code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文