Karl Barker
Karl Barker

Reputation: 11341

Dynamic Strategy Pattern

So I'm writing a web service architecture which includes FunctionProvider classes which do the actual processing of requests, and a main Endpoint class which receives and delegates requests to the proper FunctionProvider.

I don't know exactly the FunctionProviders available at runtime, so I need to be able to 'register' (if that's the right word) them with my main Endpoint class, and query them to see if they match an incoming request.

public class MyFunc implements FunctionProvider{
  static {
    MyEndpoint.register(MyFunc);
  }
  public Boolean matchesRequest(Request req){...}
  public void processRequest(Request req){...}
}

public class MyEndpoint{
  private static ArrayList<FunctionProvider> functions = new ArrayList<FunctionProvider>();
  public void register(Class clz){
    functions.add(clz);
  }
  public void doPost(Request request){
    //find the FunctionProvider in functions
    //matching the request
  }
}

I've really not done much reflective Java like this (and the above is likely wrong, but hopefully demonstrates my intentions).

What's the nicest way to implement this without getting hacky?

Upvotes: 1

Views: 1033

Answers (1)

user45886
user45886

Reputation:

  • Do not let the FunctionProviders self register. Bootstrap the endpoint through some application init. call with a list of FunctionProviders. That way you can configure priority (what if two providers both claim they can process a request?). The way you set it up now you need to invoke the class somehow to trigger the static constructor, too indirect.
  • If detecting whether or not a FunctionProvider supports a given request is trivial consider making it part of configuration. If this is in the request map it to that FunctionProvider. This would seperate concerns a bit better. If the detection is complicated consider doing it in seperate classes from the FunctionProvider.
  • By configuring a delegate/function pointer you can possibly prevent from needing a FunctionProvider altogether (not sure if/how Java supports delegates).

Upvotes: 2

Related Questions