Guice로 구현하려는 Factory Class 유스 케이스가 있습니다. 사용자가 내 앱에서 수행 할 수있는 다양한 종류의 액션을 나타내는 액션이라는 추상 클래스가 있습니다. 각 액션은 Action 클래스의 서브 클래스이며, 각각은 String 타입의 ID를 가지고 있습니다. 조치는 무거운 물건이기 때문에 한 번에 모두 인스턴스화하지 않으려 고하므로 클라이언트가 요청한 ID에 따라 각 인스턴스를 초기화하는 팩토리를 제공합니다. 이 공장의Guice String id에 따라 다른 하위 클래스 인스턴스를 어떻게 제공 할 수 있습니까?
public interface ActionFactory {
Action getActionByID(String id);
}
우리의 구현이 문자열 인스턴스와 콘크리트 작업 인스턴스를 제공하는 소위 ActionInstantiator 사이의 관계를 유지하기는 HashMap을 사용하여 같은
는 공장 인터페이스 보인다. 이것의 구현과 같이 보인다 :
public class ActionFactoryImpl implements ActionFactory {
private HashMap<String, ActionInstantiator> actions;
private static ActionFactoryImpl instance;
protected ActionFactoryImpl(){
this.actions=new HashMap<String, ActionInstantiator>();
this.buildActionRelationships();
}
public static ActionFactoryImpl instance(){
if(instance==null)
instance=new ActionFactoryImpl();
return instance;
}
public Action getActionByID(String id){
ActionInstantiator ai = this.actions.get(id);
if (ai == null) {
String errMessage="Error. No action with the given ID:"+id;
MessageBox.alert("Error", errMessage, null);
throw new RuntimeException(errMessage);
}
return ai.getAction();
}
protected void buildActionRelationships(){
this.actions.put("actionAAA",new ActionAAAInstantiator());
this.actions.put("actionBBB",new ActionBBBInstantiator());
.....
.....
}
}
그래서,이 팩토리를 사용하고 ActionAAA 인스턴스 클래스는 다음과 같이 그것을 호출 원하는 수있는 몇 가지 클라이언트 : 가가 데이터베이스에서 실행 얻었다의 actionId
Action action=ActionFactoryImpl.instance().getActionByID(actionId);
.
어떤 종류의 주석 주입이 비슷한 것을 할 수 있다는 것을 알았지 만, 제 경우에는 런타임에 사용자가 다시 시작할 인스턴스 만 알고 있기 때문에 제 생각에는 작동하지 않을 것이라고 생각했습니다. 주석을 달 수 없었습니다. 코드에.
저는 Guice를 처음 사용하기 때문에 문서에서 찾을 수없는 매우 일반적인 내용 일 수 있습니다. 도움이 될 것입니다. 감사합니다 다니엘
답장을 보내 주셔서 감사합니다. 콜린, 내 서버에 Guice 3.0을 사용하는 해결책이 될 수 있다고 생각합니다. 하지만 GWT 클라이언트 측에서 Gin 1.5로 구현할 수있는 솔루션이 필요합니다. –
@Daniel :'bind (ActionFactory.class) .to (ActionFactoryImpl.class)'? – ColinD