GWT的ActivityMapper是否违反了Liskov替换原则? [英] Does GWT's ActivityMapper violate the Liskov Substitution Principle?

查看:120
本文介绍了GWT的ActivityMapper是否违反了Liskov替换原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的GWT应用程序中,我有一个类如下所示:

  public class AppActivityMapper implements ActivityMapper {

@Override public Activity getActivity(Place place){

if(place instanceof ThisPlace){
return this ThisActivity((ThisPlace)place);
}
if(place instanceof ThatPlace){
return new ThatActivity((ThatPlace)place);
}
if(place instanceof AnotherPlace){
return AnotherActivity((AnotherPlace)place);
}
//你的想法是
}
}

ActivityMapper,Activity和Place对象是框架的一部分,接口意味着这就是它的意图。



然而,根据 Liskov Substitution Principle ,一种接受类型但是类型的方法检查子类来推断采取的行动是违反原则的。



GWT的ActivityMapper接口本质上是否鼓励违反LSP?或者是否有另一种符合LSP标准的方法来编写我没有想到的方法?

code> ActivityMapper 是将 Place 映射到 Activity ,其中映射规则完全免费。

这种if / else级联的原因是Java不支持多次调度,但在我看来,这并不意味着它违反了LSP(或者至少,在Java中你没有别的选择,所以这不是问题;你可以使用访客模式 - 这就是Spring Roo生成的模式 - 但这不会改变很多事情)。


In my GWT application, I have a class like so:

public class AppActivityMapper implements ActivityMapper {

    @Override public Activity getActivity(Place place) {

        if(place instanceof ThisPlace) {
            return new ThisActivity((ThisPlace)place);
        }
        if(place instanceof ThatPlace) {
            return new ThatActivity((ThatPlace)place);
        }
        if(place instanceof AnotherPlace) {
            return new AnotherActivity((AnotherPlace)place);
        }
        // you get the idea
    }
}

The ActivityMapper, Activity, and Place objects are part of the framework, and the interface implies that this is how it was meant to be used.

However, according to the Liskov Substitution Principle, a method that accepts a type but does a type check for subclasses to infer what action to take is a violation of the principle.

Is GWT's ActivityMapper interface by nature encouraging a violation of the LSP? Or is there another LSP-compliant way to code that method that I haven't thought of?

解决方案

The role of the ActivityMapper is to map a Place to an Activity, where the rules for the mapping are left entirely free.
What makes for that kind of if/else cascade is that Java doesn't support multiple dispatch, but in my opinion it doesn't mean it's violating the LSP (or at least, well, you have no other choice in Java, so it's a non-issue; you could use a visitor pattern –that's what Spring Roo generates– but that doesn't change much things).

这篇关于GWT的ActivityMapper是否违反了Liskov替换原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆