interface Parent{
void process();
}
class Child1 implements Parent{
void process(){
//process by method 1
}
}
class Child2 implements Parent{
void process(){
//process by method 2
}
}
class DummyChild implements Parent{
void process(){
//do nothing
}
}
class D {
Parent getObj(){
if(condition1){
return new Child1();
}
else if(condition2){
return new Child2();
}
else
return new DummyChild();
}
public static void main(String[] args){
Parent obj = getObj();
obj.process();
}
}
In the above code, I have created a DummyChild class so that whenever getObj() is invoked for fetching the correct class object, instead of returning NULL I return the dummyClass object(singleton). This eliminates the NULL check in my code thereby removing the branching because of this condition.
Is this a correct place of using the NULL object pattern or should I use the NULL approach?
Aucun commentaire:
Enregistrer un commentaire