Declaring an object that extends a class and implements more than one interface
https://softwareengineering.stackexchange.com/questions/395762
-
28-02-2021 - |
문제
I'm confused about how should I declare an object that implements more than one interface, or derives from a class that implements one interface, and implements another interface itself.
Let's suppose I have a generic DAO interface, as follows:
public interface IDao<T> {
Optional<T> get(long id);
List<T> getAll();
void save(T t);
void update(T t, String[] params);
void delete(T t);
}
Then, I also have an implementation for this interface:
public class DaoImpl implements IDao<Entity> {
//implementation goes here
}
In my understanding, if I'd like to use this DAO implementation in another class, I should declare the object as an IDao
, instead of DaoImpl
, in order to be able to change the implementation without modifying the class. See below:
public class MyClass {
IDao dao;
public MyClass(IDao dao) {
this.dao = dao;
}
}
However, suppose I want to create an implementation that extends the DaoImpl
and adds functionality, for example:
public class FilterDaoImpl extends DaoImpl implements IFilterDao<Entity> {
public List<Entity> getBetweenDates(Date start, Date end) {
//...
}
}
I believe I should also create an IFilterDao
interface and make the FilterDaoImpl
implement it. I'm not sure how to declare this implementation in a class. If I do it like this:
public class MyClass2 {
IFilterDao dao;
public MyClass(IFilterDao dao) {
this.dao = dao;
}
}
I won't be able to call methods like getAll()
.
How should I declare the FilterDaoImpl
implementation in a class?
해결책
If the idea is that a FilterDao includes all of the behaviours that a regular Dao does, then you can make FilterDao extend the Dao interface. e.g.
public interface FilterDao extends Dao {
you can then extend the implementation to avoid reimplementing methods:
public class FilterDaoImpl extends DaoImpl implements FilterDao {
By the way, most Java conventions prefer not to prefix interface names with "I".
다른 팁
I believe what you want to have a Normal Dao which will read data from DB and then have a FilteredDao which will get Data and the apply filter and return it.
Composition over Inheritance
You can do this way.
Have class IDAO
public interface IDao { public String getData(); }
Dao Impl
public class DaoImpl implements IDao { public String getData() { return "Hello world"; } }
IFilterDao
public interface IFilterDao { public String getFilteredData(); }
IFilterDaoImpl
public class IFilterDaoImpl implements IFilterDao { private IDao iDao; public String getFilteredData() { String data = iDao.getData(); //apply some filter return data; } }
Now the IFilterDaoImpl will have all the functionality of IDAO. No matter what impl of DAO being used.