mardi 31 mars 2015

Pattern for "Varied Parameters"

I am trying find out the best way to pass "varied parameters" through a method in interface. I created a solution that worked, but my concern is it will be used for thousand of GLResource objects. So, I would like to know if this solution is an anti-pattern or if there is another known solution for this kind of situation. I just want avoid refactoring it in the future.


Let's demonstrate:



At first, I created an interface that represents a OpenGL resource, that I called GLResource, and it have to be implemented by all OpenGL Resource.




public interface GLResource {
public void onSurfaceCreated(VariedParameters variedParameters);
public void onSurfaceChanged(VariedParameters variedParameters);
public void deleteResources();
public void onDrawFrame(Canvas canvas);
}



Basically, all OpenGL resource configuration will be passed through VariedParameters class. And sometimes you can pass a texture or vertex data, or another kind of object configuration.


The implementation of VariedParameters is simple:




class VariedParameters <K extends Enum<K>> {
private Map<K, Object> parametersMap = new HashMap<>();

public VariedParameters<K> putParameter(K key, Object value){
parametersMap.put(key, value);

return this;
}

public Object getParameter(K key){
return parametersMap.get(key);
}

public void clear(){
parametersMap.clear();
}
}



An implementation of GLResource could be:




public class Car implements GLResource{

@Override
public void onSurfaceCreated(VariedParameters variedParameters) {
Texture carTexture = (Texture) variedParameters.getParameter(CarParameters.CAR_TEXTURE);
Texture wheelTexture = (Texture) variedParameters.getParameter(CarParameters.WHEEL_TEXTURE);
Foo foo = (Foo) variedParameters.getParameter(CarParameters.FOO);

if(carTexture == null || wheelTexture == null || foo == null){
throw new IllegalArgumentException("Some arguments is missing.");
}

// Work with these parameters...
}

@Override
public void onSurfaceChanged(VariedParameters variedParameters) {
// TODO Auto-generated method stub
}

@Override
public void deleteResources() {
// TODO Auto-generated method stub
}

@Override
public void onDrawFrame(Canvas canvas) {
// TODO Auto-generated method stub
}

public enum CarParameters{
CAR_TEXTURE,
WHEEL_TEXTURE,
FOO;
}
}



And below is an example of code that will use all GLResource implementation:




public class Main {

public static void main(String[] args) {
Car car = new Car();

VariedParameters<CarParameters> carVariedParameters = new VariedParameters<>();
carVariedParameters.putParameter(CarParameters.CAR_TEXTURE, new Texture());
carVariedParameters.putParameter(CarParameters.WHEEL_TEXTURE, new Texture());
carVariedParameters.putParameter(CarParameters.FOO, new Foo());

car.onSurfaceCreated(carVariedParameters);
}

}


So, what do you think about this pattern?


Aucun commentaire:

Enregistrer un commentaire