I’ve worked in a project where I implemented an API based on an international standard called SCORM (it stands for Shareable Content Object Reference Model). It was developed to be used by e-learning systems and courses. While implementing the API, I needed to model some classes for the data types supported by SCORM version 1.2, keeping in mind that they have some common attributes and specific validation methods. There are 15 different types, and all that classes (one for each type) in my diagram was bothering me.
Considering that all the classes derive from an abstract class named ScormObject, I’ve had the idea of using the Abstract Factory Pattern. By doing this, I was able to put all that related validation code together into one “factory” class, turning the old classes into static subclasses inside the factory. This new class, named ScormObjectFactory, has methods for creating all the 15 types. I’ve started coding the class as below (note that in this project I’ve used Java):
/**
* <p>Factory of ScormObjects, following the Abstract Factory pattern</p>
*
* @version 1.1
*/
public class ScormObjectFactory {
private static final int CMIIDENTIFIER = 1;
private static final int CMIBLANK = 2;
private static final int CMISTRING255 = 4;
private static final int CMISTRING4096 = 8;
private static final int CMIINTEGER = 16;
private static final int CMISINTEGER = 32;
private static final int CMIDECIMAL = 64;
private static final int CMITIME = 128;
private static final int CMITIMESPAN = 256;
private static final int CMIVOCABULARY = 512;
private static final int CMISCORE = 1024;
private static final int CMIAUDIO = 2048;
private static final int CMISPEED = 4096;
private static final int CMITEXT = 8192;
private static final int CMIFEEDBACK = 16384;
}
Then, I’ve written a subclass for each one of the types. The code below is from the CMIIdentifier type implementation.
/**
* <p>This class extends ScormObject representing the CMIIdentifier type,
* and does the specific validation of this type.</p>
*
* @version 1.1
*/
private static class ScormObjectCMIIdentifier extends ScormObject {
public ScormObjectCMIIdentifier() {
super();
}
/**
* <p>Checks if the info value is a valid CMIIdentifier.
*
* @return Returns true if the value is a valid CMIIdentifier.
*/
public boolean validate(String info) {
if( info.indexOf(” “) != -1 || info.length() > 255 || info.compareTo(“”) == 0 )
return false;
else
return true;
}
public int getDataType(){
return CMIIDENTIFIER;
}
}
Note that each type has its own implementation of the validatemethod. Finally, I create methods to turn the types public through the application code. See the example below for the CMIdentifier subclass.
public static ScormObjectCMIIdentifier createCMIIdentifier(){
return new ScormObjectCMIIdentifier();
}
Now, I can use the type anywhere in the code by calling the ScormObjectFactory.createCMIIdentifier method.
Tiago Braga said
Thanks a lot!