I would like to create a factory class which creates some Dialogs (actually AlertDialog) with different characteristics depending from which class is called. For example, if I call the Factory.createDialog() from class A, it gives me an AlertDialog with some button text, from class B - the same button has a different text. My question is how should I implement the Factory:
Variant 1:
public class DialogFactory {
public static Dialog createDialog(String className){
if(class A){
return DialogForClassA.buildDialog();
}
else if(class B){
return DialogForClassB.buildDialog();
}
//else ...
}
}
interface MyDialog {
static Dialog buildDialog();
}
class DialogForClassA implements MyDialog{
public static Dialog buildDialog(){
//create dialog
return dialog;
}
}
class DialogForClassB implements MyDialog{
public static Dialog buildDialog(){
//create dialog
return dialog;
}
}
Variant 2:
public class DialogFactory {
public static Dialog createDialog(String className){
//Build the dialog common features
//....
//add the features that are different
if(class A){
//set button textA;
}
else if(class B){
//set button textB;
}
//else ...
return dialog;
}
}
Also, please advise me if there is something wrong with the logic.
For example, is something wrong if the method buildDialog() is static in classes A and B?
Is there any better alternative?
Actually I think the first variant is incorrect, you cannot really use static methods in interfaces, at least that way.
You may use a standard method in variant 1:
interface Dialog { public Dialog buildDialog(); }
public class DialogFactory { public static Dialog createDialog(String className){ if(class A){ dialog = new DialogForClassA(); } else if(class B){ dialog = new DialogForClassA(); } return dialog.buildDialog(); } }
But I don't see any advatage in declaring an interface method to build the dialog (unless you use RTTI, but this is another topic... BTW: You can still make use of Reflection in both variants if you need, and the two variants in that case will look identical!).