Skip to content

2. Custom Ecore Factories

Timur Sağlam edited this page Sep 3, 2017 · 3 revisions

Customized Ecore Factories

EMF creates a package and a factory class for every EPackage when generating model code from an Ecore metamodel. These factories allow creating instances of the types contained in the package. Every factory consists of an interface and an implementation class. While it is not necessary to use the factories for the instantiation of the types in the package, EMF highly encourages it. Additionally, many tools like model transformation languages use these factories

The factories in the Ecore model code are creating instances of the implementation classes of the Ecore Code. If we want to use our ecorified Code as we would normal model code generated from Ecore metamodels, the factories have to create instances of the classes from the origin code. To achieve that, we have to create adapted factories. It is important to keep the original factories as well because they are needed to create instances of the Ecore code implementation classes for the integration code.

To keep the original factories intact, we rename them. The custom factories are identical to the orignal factories but they create origin Code instances. They contain adapted methods in the implementation classes of the factories to return the correlating class of the original code instead of the Ecore code implementation class. For the Ecore code class ECustomer of the example the original instantiation method in the factory class looks like this:

public ECustomer createECustomer() {
    ECustomerImpl customer = new ECustomerImpl();
    return customer;
}

An instance of the class ECustomerImpl is created and returned. The method declares the return type ECustomer. This can be easily altered to create an instance of the class Customer of the origin code by changing the method body:

public ECustomer createECustomer() {
    return new Customer();
}

While the declared return types stay the same, the actual return type is changed. After copying the factories and adapting the original ones the ecorified code can be used as one would normal model code. While the interfaces of the adapted factories do not show any change, internally, classes of the origin code are instantiated.

Implementation

This process is implemented using the classes FactoryRenamer and EcoreFactoryGenerator. The class FactoryRenamer in the package jce.codemanipulation.ecore is used the rename the original factories. All compilation units of the Ecore code are filtered for factory types and then renamed using Eclipse LTK refactorings. The class EcoreFactoryGenerator in the package jce.generators uses two lasses (EFactoryGenerator and EFactoryImplementationGenerator) two generate the custom factories. Both classes are subclasses of the ClassGenrator, which allows the generation of Java and Xtend classes.

Clone this wiki locally