What are Switch classes used for?

帅比萌擦擦* 提交于 2019-12-12 17:39:13

问题


What are switch classes (derived from org.eclipse.emf.ecore.util.Switch<T>) used for?

The javadoc explains it as

An abstract base class for all switch classes.

which does not help as I have never heared about "switch classes" before.


回答1:


A switch class is a class that allows you to choose and instantiates a concrete instance of a type based on a model object (in this case, an EMF model object). The examples I've seen suggest it's useful for instantiating type-specific adapters for an EMF model.

You use it by overriding the doSwitch method. For instance, say I've got a model object, and I want to instantiate an adapter object that corresponds to the type value in my model:

public class ExampleSwitch extends Switch<Adapter> {

    public Adapter doSwitch(EObject eobject) {
        if (eobject instanceof MyModel) {
            switch (eobject.getType()) {
                case TYPEA:
                    Adapter result = createTypeAAdapter(eobject);
                    if (result == null) {
                        return createDefaultAdapter(eobject);
                    }
                    return result;
                case TYPEB:
                    ...
                default:
            }
        }
    } 
}

An eclipse org.eclipse.emf.common.notify.AdapterFactory would then use this to return an Adapter.

public class MyAdapterFactory implements AdapterFactory {
    public boolean isFactoryForType(Object o) {
        return (o instanceof MyModel);
    }
    public Adapter adapt(Notifier notifier, Object type) {
        return mySwitch.doSwitch((EObject)notifier);
    }
}  

I've pulled this information from here. I haven't verified this, but apparently the EMF generator can optionally generate your AdapterFactories and Switch classes for you.




回答2:


Everything in Java is class. (Except primitives). So when you use switch, behind the scenes you call a class that has all the logic for switch. Switch<T> is probably class from which other switch classes inherit and implement methods when you use them. For example you can use switch(int) or you can use switch(String) and both functionalities are different and have to be defined somewhere.



来源:https://stackoverflow.com/questions/33705614/what-are-switch-classes-used-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!