Recently I came up with the idea of simple pattern for dynamic creation of object. And I real love it.
I am sure that that “wheel” was invented and named. Could someone could point to some GOF pattern?
Problem: have huge number of objects that I don’t want to have all initialized at the beginning. All are instances of one class.
I want to use an object and then free the memory (or allow garbage collection),
each object is correlated to some string, so I have a map ({“str1”, obj1}, {“str2”,obj2},…)
When the request comes with str1 I need to return obj1,….
I could have (pseudocode)
if(str == str1)
return new Obj(obj1_init_params);
else if(str == str2)
return new Obj(obj2_init_params);
…
However this is:
- Inefficient – to go over all if conditions.
- Ugly:)
To solve 1. you could use map:
map.put(str1, new Obj(obj1_init_params))
map.put(str2, new Obj(obj2_init_params))
then:
map.get(str1)
This is fast solution but ALL IS ONCE created not on demand. So….
Create a wrapper interface:
IWrapper {
Obj getObj();
}
Then I put it in map:
map.put("str1", new IWrapper(){Obj getObj() {return new Object(object1_params)};
Now I am in home:
- Fast: map.get(“str1”).getObj();
- Dynamic – getObj() <- creation of object is postponed.
It is so simple, nice that someone had named it before.
I am java programmer, so it work nice here. Can you came with similarly elegant solution?
EDIT I’ve mixed “what” with “how”, originally.
What have you achieved? A lazy initialization.
How have you achieved it? Through the Factory pattern (as many others have already written).
UPDATE You can use the standard
Callableinterface instead ofIWrapper: