Java: using inheritance if only constructor differs

adolzi :

I need to implement the same sequence of commands in a service, but operating on several different database objects, depending on a case. I'm wondering whether it is a good practice to use an inheritance in such case - which would consist in passing a different dao in a specifc class's constructor only. Something like this:

 public abstract class Service{

   private Dao dao;

    public Service(Dao dao){
        this.dao = dao;
    }

    public void mainMethod(){
        dao.step1();
        subMethod();
        dao.step2();
    }

    public void subMethod(){
       //...
    }
}


public class ServiceImpl1 extends Service{

   public ServiceImpl1(DaoImpl1 daoImpl1){
       super(daoImpl1);
   }
}
munk :

Inheritance is useful for delegating messages (method calls) to the superclass with few changes. You're not delegating messages to the parent class though, you're changing the parameter of the constructor. So there is no need to inherit anything.

This is fine:

public class Service{ 
    private Dao dao;

    public Service(Dao dao){
        this.dao = dao;
    }

    public void mainMethod(){
        dao.step1();
        subMethod();
        dao.step2();
    }

    public void subMethod(){
       //...
    }
}

You can then make instances like

Service posgresService = new Service(new PosgresDao());
Service redisService = new Service(new RedisDao());

See depenency injection for more details

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=104626&siteId=1