Lets say you have a business flow that evolves around creating multiple queries on a songs database, and you have some steps in all
The example is in Spring Boot but the logic can be applied anywhere
- Have a factory that decides the query
- Parse: Receive some data, break them down, create the query
- Query: Perform query on repository, the query returns a
List<SongItem> - PrepareAnswer: Create a return DTO
Steps 2, 4, have different implementations, thus the different classes
you can create an interface or abstract class Query
private interface Query(){
public ?? parse();
public QueryBuilder createQuery();
public ?? PrepareAnser();
}
and implement multiple Query types like RockQuery PopQuery FolkQuery
public class RockQuery implements Query
How should the service be organized and the data List<SongItem> carried around the several steps?
I have several thoughs, its mostly wether to include the SongList in the class or keep it in the Service
1)
@Service
public class SongService()
public SongListDTO makeAList(Data data){
@Autowired
SongRepository repository;
Query query = factory(data).getQuery(Type.ROCK); // or something similar
List<SongItem> songs = repository.query(query.createQuery());
return query.prepareAnswer(songs);
}
instead of creating a different querytype, actually perform the query inside the QueryClass, not the Service. Of course inject the repository there.
Keep the List<SongItem> as class member. Dont expose it to the Service
public SongListDTO makeAList(Data data){
Query query = factory(data).getQuery(Type.ROCK); // or something similar
query.performQuery()
return query.prepareAnswer(songs);
}
- Something similar, multiple variations may apply
I did not follow the code snippet you provided, but you can follow the following approach:
In this example, the
SongServiceclass is the service class that coordinates the different steps. TheSongRepositoryis a Spring Data JPA repository interface that handles the database interactions.The
QueryFactoryandPrepareAnswerFactoryare factory classes that provide instances of the corresponding Query andPrepareAnswerimplementations based on thequeryTypeparameter.The
getSongsByQueryTypemethod takes in thequeryTypeparameter, which determines the type of query required. It then creates an instance of the correspondingQueryimplementation using theQueryFactory, parses the data, creates the query, and executes it on the repository.The
List<SongItem>result is then passed to the correspondingPrepareAnswerimplementation, created using thePrepareAnswerFactory, to create the return DTO.