简体   繁体   中英

Which design pattern to use to iterate over request attributes in spring boot

I have a requirement to save the request entity into multiple data sources. My request can have one or more request objects and they should be saved in respective databases. Which design patterns suits the requirement?

HTTP Request

{
  "params" : [ 
    {
       "id": "AB",
       "data": //some object
    },
    {
       "id": "CD",
       "data": //some object
    },
    {
       "id": "EF",
       "data": //some object
    },
    {
       "id": "GH",
       "data": //some object
    },
    {
       "id": "IJ",
       "data": //some object
    },
    ...........
    ...........
  ]
}

AB & CD - to ORACLE instance 1
EF & GH - to ORACLE instance 2
IJ - to MYSQL

Here I know which object should be saved in which database. I don't want to iterate through the params array and create multiple small arrays, unless that's the only option. I'm looking here to apply a design pattern which will take care of the purpose, can someone please suggest?

I think the best design pattern, in this case, is the [Factory method pattern][1] . Indeed you will create an appropriate object by the client data. I mean according id value the relevant service will call to save data into the respective database.

suppose you will have an interface for saving data with different implementations.

public interface IService {

   void save(Data data);

   List<String> types();
}

and their implementations are something like these:

@Service
class OracleInstance1 implements IService {

   void save(Data data){}

   List<String> types(){return List.of("AB","CD");}
} 

for mysql instance:

@Service
class MysqlInstance implements IService {

  void save(Data date){}

  List<String> types(){return List.of("IJ");}
} 

now you need a factory method to create a relevant object based on data entry.( id ) for create a factory method I create a new service with ServiceHolder name. In this class all implementations of base service will use. because you use spring framework, it will do in easily. just by auto wiring a list.

@Service
class ServiceHolder{

  @Autowired
  List<IService> allService;


  public IService getByType(String type){
     return allService.stream()
            .filter(s->s.getTypes().contains(type))
            .findFirst().orElse(null);
  }
} 

now by performing this service and looping over data entries you can save in its own database.

for(MyParam param: params){
  serviceHolder.getByType(param.getId()).save(param.getData()); 
}

by using getByType method you can find appropriate service for every data entry and call save method to insert into database. [1]: https://en.wikipedia.org/wiki/Factory_method_pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM