Reputation: 31
I am trying to figure out a design pattern to use (if any exists) to a situation where I would be re-doing some functionality across a bunch of classes. Below is a (simplified) overview of the problem I am facing:
I have some Java code to CREATE, UPDATE, DELETE Student
objects, Professor
objects, & Staff
objects. And every time such an object is either created, deleted, or updated, I want to extract some information about the affected object (such as name, age, id) and notify an external service. So something like:
class StudentDAO {
public Student createStudent(Student studentToCreate) {
jdbcTemplate.update(INSERT_SQL, .....);
//===> extract some info of the student
//let external service know a student was created....
}
public Student deleteStudent(Student studentToDelete) {
jdbcTemplate.update(DELETE_SQL, .....);
//===> extract some info of the student
//let external service know a student was deleted....
}
//same thing for update
}
class ProfessortDAO {
public Professor createProfessor(Professor professorToCreate) {
jdbcTemplate.update(INSERT_SQL, .....);
//===> extract some info of the professor
//let external service know a Professor was created....
}
public Student deleteProfessor(Professor professorToDelete) {
jdbcTemplate.update(DELETE_SQL, .....);
//===> extract some info of the professor
//let external service know a professor was deleted....
}
//same thing for update
}
//repeat for Staff
The example is bit contrived but assume that Student
, Professor
, Staff
share no common supertype. Is there a way to achieve this functionality without copying and pasting the logic for extracting the info and sending it in all the DAO classes for CREATE, DELETE, UPDATE methods ?
Upvotes: 2
Views: 341
Reputation: 620
You should search for Generic Repository. You can learn more here:
https://www.youtube.com/results?search_query=generic+repository+java
Sample Code:
class Reposiory<T> {
public T create(T Create) {
jdbcTemplate.update(INSERT_SQL, .....);
}
public T delete(T Delete) {
jdbcTemplate.update(DELETE_SQL, .....);
}
}
Upvotes: 1
Reputation: 40057
Not much info to go on but have you considered using generics
for a specific type and implementing an interface
to define the common information (phone, name, id)
you want to access from each type of individual?
You should also be able to pass the operation (DELETE, ADD, UPDATE)
as an argument. I would suggest using an enum
for that.
Upvotes: 0
Reputation: 1060
You can use aspect oriented programming. You can then write a general point cut which matches all your methods where you want to talk to your external server. What is aspect-oriented programming?
Upvotes: 0
Reputation: 8322
Create ReportExternalService interface and add key property, Implement this Interface if the object requires to be notified.
Create one method which takes the parameter as ReportExternalService and use key to report to external service.!
Upvotes: 0