dimanche 9 avril 2023

Java Design Pattern for initializing dynamic private variable

I have an interface named IClientServer.java

interface IClientServer {
   void save(String fileName);
}

It's Impl looks this way:

public class ClientServerImpl implements IClientServer {

    private final String key;
    private final Client client;

    public ClientServerImpl(final String key1, final String key2) {
        this.key = key1 + key2;
        this.client = openConnection(key);
    }

    @Override
    public void save(String fileName) {
    client.save(fileName);
....
  }
}

Note that the above Interface and Impl are in a common project accessible to all projects and every project currently using this initialize the bean per their own keys at the configuration level and use them directly.

I now have to create an API that is also in a common project that will need to access the ClientServer

New class: IClassA.java

public interface IClassA {
   void save(boolean validate, String fileName);
}

It's Impl:

public class classA implements IClassA {

    private final IClientServer clientServer;

    public classA(IClientServer clientServer) {
        this.clientServer = clientServer;
    }

    @Override
    public void save(boolean validate, String fileName) {
    //perform computation and then proceed to save
    clientServer.save(fileName);
....
  }
}

Now, classA.save() is invoked after consuming a Kafka Record from the topic.

Since IClassA is also in the common library, how do I initialize ClientServerImpl with dynamic keys specific to the caller?

PS: I can have both the keys as part of the kafka record if it's needed.

Aucun commentaire:

Enregistrer un commentaire