I have 2 questions on what are the pros/cons of the following design for factories and builders: 1. static factory class inside an interface 2. static builder class inside an interface
Note: Here i am using HK2 for dependency injection. So @Contract annotates an interface while @Service represents an implementing class. The ServiceLocatorFactory will return an instance of the implementing class using HK2 dependency injection framework
Code sample#1: (static factory class inside an interface)
package org.swx.nursing.tools.sqlfinder.gui;
import java.awt.event.ActionListener;
import org.jvnet.hk2.annotations.Contract;
import prg.swx.nursing.tools.sqlfinder.servicelocator.ServiceLocatorFactory;
@Contract
public interface GuiTemplate extends ActionListener {
public void createAndShowGUI(GuiTemplateCriteria guiCriteria);
public static final class Factory{
//Disable public instantiation
private Factory (){
throw new AssertionError();
}
public static GuiTemplate create(){
return
ServiceLocatorFactory.getInstance().getService(GuiTemplate.class);
};
}
}
Code Sample#2 (static builder class inside an interface):
package org.swx.nursing.tools.sqlfinder.gui;
import org.jvnet.hk2.annotations.Contract;
import prg.swx.nursing.tools.sqlfinder.servicelocator.ServiceLocatorFactory;
@Contract
public interface GuiTemplateCriteria {
public String getDefaultMessageText();
public static final class Builder {
protected String defaultMessageText;
/**
* Declared private to prevent direct instantiation by external consumers.
*/
private Builder() {
}
/**
* Creates a new Builder.
* @return Non-null Builder.
*/
public static Builder create()
{
return new Builder();
}
public Builder withDefaultMessageText(final String defaultMessageText)
{
this.defaultMessageText = defaultMessageText;
return this;
}
public GuiTemplateCriteria build()
{
return ServiceLocatorFactory.getInstance().getService(GuiTemplateCriteria.class);
}
}
}
In code sample 1 and 2, the factory and the builder can also be moved to the implementing classes or separate class. If i take the above approach, how good or bad the design is or what kind of discussion can be had on such a design.
Please advise
Thanks!
Aucun commentaire:
Enregistrer un commentaire