消除GWT ActivityMapper样板

时间:2011-04-27 10:39:30

标签: gwt gwt-mvp gin

我正在使用GWT Activities and Places框架来构建我的应用程序,结果很好。令我恼火的一件事是ActivityMapper实现是(1)接收应用程序中的所有视图(2)包含一个巨大的if / else块,用于根据接收到的地点实例化活动。随着观看次数的增加,它只会变得更糟。

ActivityMapper screenshot

我已经在使用Gin,但我不知道如何在这里使用它。

如何从ActivityMapper

中减少或消除样板

5 个答案:

答案 0 :(得分:3)

还没有很好的答案。我考虑到了代码生成方案,但目前在白板上都是涂鸦。对于Gin用户来说,放置范围似乎很方便。

Re:if / else级联,一种常见的方法是让Place对象实现访问者模式。例如。让我们假设您已经为您的活动设置了AssistedInject(并且原谅了草率的场注入,它只是一个草图)。

class BasePlace extends Place {
    <T> T acceptFilter(PlaceFilter filter);
}

interface PlaceFilter<T> {
  T filter(FooPlace place);
  T filter(BarPlace place);
  T filter(BazPlace place);
}

public class MainActivities implements ActivityMapper {
  @Inject FooFactory fooMaker;
  @Inject BarFactory barMaker;
  @Inject BazFactory bazMaker;

  public Activity getActivity(PlaceChangeEvent e) {
     return ((BasePlace)e.getPlace()).acceptFilter(
       new PlaceFilter<Activity>() {
         Activity filter(FooPlace place) {
           return fooMaker.create(place);
         }
         Activity filter(BarPlace place) {
           return barMaker.create(place);
         }
         Activity filter(BazPlace place) {
           return bazMaker.create(place);
         }
       })         
   }
}

答案 1 :(得分:2)

一种可能性是让Place类层次结构的根定义createActivity()方法,而Place子类可以返回与它们关联的Activity的新实例。

@Override
public Activity getActivity(Place place) {
    return ((BaseAppPlace)place).createActivity();
}

这样做的好处是消除了if / else块,并在添加新的Place / Activity时减少了一个地方。这样做的缺点是,即使您只是委托给Ginjector,它也可以通过Activity创建行为来污染您的Place类。

答案 2 :(得分:1)

实际上我正在使用自定义样板代码执行此任务:

public class PuksaActivityMapper implements ActivityMapper {
private HashMap<String, ActivityContainer> mappings;

@Inject
private SearchResultActivityContainer searchResultContainer;
@Inject
private HelloActivityContainer helloContainer;

@Override
public Activity getActivity(Place place) {
    ActivityContainer container = getMappings().get(place.getClass().getName());

    return container.getActivity(place);
}

public HashMap<String, ActivityContainer> getMappings() {
    if (mappings == null) {
        mappings = new HashMap<String, ActivityContainer>();

        mappings.put(ShowResultsPlace.class.getName(), searchResultContainer);
        mappings.put(HelloPlace.class.getName(), helloContainer);
    }
    return mappings;
}

}

其中ActivityContainer是一个简单的工厂类型(从这一点开始可以使用经典的ioc方法)。

当然现在只更改'if block'并使用地图查找/填充,但结合Gin multibinding(当前不存在)可以完成它的工作。

同样Gin enhancement - GWT活动/地方的通用GinModule看起来很有希望。

答案 3 :(得分:1)

仅供将来参考,像我这样的人降落在这里仍然没有答案。 我最终使用GIN和Generators为PlaceFactory提供了以下解决方案。

这就是我的令牌现在的样子。例如:#EditUser / id:15 / type:Agent

我有一个AbstractPlace,每个Place都应该扩展。

public abstract class AbstractPlace extends Place {
    public abstract Activity getActivity();
}

示例地点:

public class EditUserPlace extends AbstractPlace {

private Long id;

private User.Type type;

//getters and setters

@Override
public Activity getActivity() {
    return App.getClientFactory().getEditUserPresenter().withPlace(this);
}
}

Deferred绑定的PlaceFactory接口:

public interface PlaceFactory {
    Place fromToken(String token);
    String toToken(Place place);
}

和注册地方类的注释

public @interface WithPlaces {
    Class<? extends Place>[] value() default {};
}

和PlaceFactoryGenerator

在您的GWT模块中设置生成器

<generate-with class="app.rebind.place.PlaceFactoryGenerator">
    <when-type-assignable class="app.client.common.AppPlaceFactory"/>
</generate-with>

public class PlaceFactoryGenerator extends Generator {

    private TreeLogger logger;
    private TypeOracle typeOracle;
    private JClassType interfaceType;
    private String packageName;
    private String implName;
    private Class<? extends Place>[] placeTypes;

    @Override
    public String generate(TreeLogger logger,
            GeneratorContext generatorContext, String interfaceName)
            throws UnableToCompleteException {

        this.logger = logger;
        this.typeOracle = generatorContext.getTypeOracle();
        this.interfaceType = typeOracle.findType(interfaceName);
        this.packageName = interfaceType.getPackage().getName();
        this.implName = interfaceType.getName().replace(".", "_") + "Impl";

        // TODO Trocar annotation por scan
        WithPlaces places = interfaceType.getAnnotation(WithPlaces.class);
        assert (places != null);

        Class<? extends Place>[] placeTypes = places.value();

        this.placeTypes = placeTypes;

        PrintWriter out = generatorContext.tryCreate(logger,
                packageName, implName);

        if (out != null) {
            generateOnce(generatorContext, out);
        }

        return packageName + "." + implName;
    }

    private void generateOnce(GeneratorContext generatorContext, PrintWriter out) {
        TreeLogger logger = this.logger.branch(
                TreeLogger.DEBUG,
                String.format("Generating implementation of %s",
                        interfaceType));

        ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(
                packageName, implName);
        factory.addImport(interfaceType.getQualifiedSourceName());
        factory.addImplementedInterface(interfaceType.getSimpleSourceName());

        factory.addImport(StringBuilder.class.getCanonicalName());
        factory.addImport(Map.class.getCanonicalName());
        factory.addImport(HashMap.class.getCanonicalName());
        factory.addImport(Place.class.getCanonicalName());

        for (Class<? extends Place> place : placeTypes)
            factory.addImport(place.getCanonicalName());

        SourceWriter sw = factory.createSourceWriter(generatorContext, out);

        sw.println("public Place fromToken(String token) {");
        sw.indent();
        sw.println("int barAt = token.indexOf('/');");
        sw.println("String placeName = token;");
        sw.println("Map<String, String> params = new HashMap<String, String>();");
        sw.println("if (barAt > 0) {");
        sw.indent();
        sw.println("placeName = token.substring(0, barAt);");
        sw.println("String[] keyValues = token.substring(barAt + 1).split(\"/\");");
        sw.println("for (String item : keyValues) {");
        sw.indent();
        sw.println("int colonAt = item.indexOf(':');");
        sw.println("if (colonAt > 0) {");
        sw.indent();
        sw.println("String key = item.substring(0, colonAt);");
        sw.println("String value = item.substring(colonAt + 1);");
        sw.println("params.put(key, value);");
        sw.outdent();
        sw.println("}");
        sw.outdent();
        sw.println("}");
        sw.outdent();
        sw.println("}\n");

        for (Class<? extends Place> placeType : placeTypes) {
            String placeTypeName = placeType.getSimpleName();

            int replaceStrPos = placeTypeName.lastIndexOf("Place");
            String placeName = placeTypeName.substring(0, replaceStrPos);

            sw.println("if (placeName.equals(\"%s\")) {", placeName);
            sw.indent();

            sw.println("%s place = new %s();", placeTypeName, placeTypeName);

            generateSetExpressions(sw, placeType);

            sw.println("return place;");

            sw.outdent();
            sw.println("}\n");

        }

        sw.println("return null;");
        sw.outdent();
        sw.println("}\n");

        sw.println("public String toToken(Place place) {");
        sw.indent();
        sw.println("StringBuilder token = new StringBuilder();\n");

        for (Class<? extends Place> placeType : placeTypes) {
            String placeTypeName = placeType.getSimpleName();
            int replaceStrPos = placeTypeName.lastIndexOf("Place");
            String placeName = placeTypeName.substring(0, replaceStrPos);

            sw.println("if (place instanceof %s) {", placeTypeName);
            sw.indent();

            sw.println("%s newPlace = (%s)place;", placeTypeName, placeTypeName);
            sw.println("token.append(\"%s\");", placeName);
            generateTokenExpressions(sw, placeType);
            sw.println("return token.toString();");

            sw.outdent();
            sw.println("}\n");
        }

        sw.println("return token.toString();");
        sw.outdent();
        sw.println("}\n");


        sw.outdent();
        sw.println("}");

        generatorContext.commit(logger, out);
    }

    private void generateTokenExpressions(SourceWriter sw,
            Class<? extends Place> placeType) {
        for (Field field : placeType.getDeclaredFields()) {
            char[] fieldName = field.getName().toCharArray();
            fieldName[0] = Character.toUpperCase(fieldName[0]); 
            String getterName = "get"  + new String(fieldName);
            sw.println("token.append(\"/%s:\");", field.getName());
            sw.println("token.append(newPlace.%s().toString());", getterName);
        }
    }

    private void generateSetExpressions(SourceWriter sw, Class<? extends Place> placeType) {
        for (Field field : placeType.getDeclaredFields()) {
            char[] fieldName = field.getName().toCharArray();
            fieldName[0] = Character.toUpperCase(fieldName[0]); 
            String setterName = "set"  + new String(fieldName);

            List<Method> methods = findMethods(placeType, setterName);

            for (Method method : methods) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (parameterTypes.length == 0 || parameterTypes.length > 1)
                    continue;

                Class<?> parameterType = parameterTypes[0];
                String exp = "%s";

                if (parameterType == Character.class) {
                    exp = "%s.charAt(0)";
                } else if (parameterType == Boolean.class) {
                    exp = "Boolean.parseBoolean(%s)";
                } else if (parameterType == Byte.class) {
                    exp = "Byte.parseInt(%s)";
                } else if (parameterType == Short.class) {
                    exp = "Short.parseShort(%s)";
                } else if (parameterType == Integer.class) {
                    exp = "Integer.parseInt(%s)";
                } else if (parameterType == Long.class) {
                    exp = "Long.parseLong(%s)";
                } else if (parameterType == Float.class) {
                    exp = "Float.parseFloat(%s)";
                } else if (parameterType == Double.class) {
                    exp = "Double.parseDouble(%s)";
                } else if (parameterType.getSuperclass().isAssignableFrom(Enum.class)) {
                    exp = parameterType.getCanonicalName() + ".valueOf(%s)";
                } else if (parameterType != String.class){
                    continue;
                }

                String innerExp = String.format("params.get(\"%s\")", field.getName());
                String wrapperExp = String.format(exp, innerExp);
                sw.println("place.%s(%s);", setterName, wrapperExp);
            }
        }
    }

    private List<Method> findMethods(Class<? extends Place> placeType, String name) {
        Method[] methods = placeType.getMethods();
        List<Method> found = new ArrayList<Method>();

        for (Method method : methods) {
            if (method.getName().equals(name)) {
                found.add(method);
            }
        }

        return found;
    }
}

我的ActivityMapper是什么样的?

public class AppActivityMapper implements ActivityMapper {

    public Activity getActivity(Place place) {
        AbstractPlace abstractPlace = (AbstractPlace)place;
        return abstractPlace.getActivity();
    }
}

我们需要一个自定义的PlaceHistoryMapper

public class AppPlaceHistoryMapper implements PlaceHistoryMapper {

    private AppPlaceFactory placeFactory = GWT.create(AppPlaceFactory.class);

    public Place getPlace(String token) {
        return placeFactory.fromToken(token);
    }

    public String getToken(Place place) {
        return placeFactory.toToken(place);
    }
}

最后是PlaceFactory,这将生成只是将你的地方类放在注释中并且快乐!

@WithPlaces(value = {
    HomePlace.class,
    EditUserPlace.class
})
public interface AppPlaceFactory extends PlaceFactory {

}

答案 4 :(得分:0)

首先,我为此创建了an issue on GWT issues,因此请为其加注星标或对其进行评论。 以下是我的表现方式:

   public abstract class PlaceWithActivity extends Place {
        public Activity getActivity();
   }

然后在你的ActivityMapper中:

Public Activity get Activity(Place newPlace) {
     return ((PlaceWithActivity) newPlace).getActivity();
 }

你所有的地方都应该扩展PlaceWithActivity。唯一的问题是向下转换会冒ClassCastException的风险。 Place有getActivity()然后你不必向下转,但它不会让你不得不将它转发给一个类。

我不喜欢的是你必须进行投射并制作PlaceWithActivity类。 如果GWT会增加对我正在做的事情的支持,那么这是不必要的。如果它们包含一个PlaceWithActivity类,你就不必这样做了,如果ActivityManager只调用PlaceWithActivity类的getActivity()方法,那么你不仅不需要强制转换,而且你不会这样做。甚至需要编写ActivityMapper!