简体   繁体   中英

Abstract class - extended classes and DAO

I have a abstract class User and 3 classes who extend from this class (Admin, Modurator, Lector).

In my db I have a table User with the data needed (UserName / Password / Security_lvl).

The connection to the database for User I do with DAO.

public class MysqlUserDao implements UserDao {
    //
    private static MysqlUserDao instance;

    //
    public static MysqlUserDao getInstance() {
        if (instance == null)
            instance = new MysqlUserDao();
        return instance;
    }
public void create(User user) {
        try {
            c = MySqlDAOFactory.getInstance().getConnection();
            //
            String sql = "insert into user values (?,?,?)";
            //
            prest = c.prepareStatement(sql);
            //
            prest.setString(1, user.getUserName());
            prest.setString(2, user.getPassword());
            prest.setInt(3, user.getRole().returnSecurityLevel());
            //
            prest.executeUpdate();
            //
        } catch (SQLException e) {
            JdbcLogging.info("error item" + " :"
                    + e);
        } finally {
            MySqlConnectionFactory.getInstance().closeResultSet(rs);
            MySqlConnectionFactory.getInstance().closeStatement(prest);
            MySqlConnectionFactory.getInstance().closeConnection(c);
        }
    }

}

In java depending on the user-type I make the specific Admin, Modurator or Lector objects so I can use their specific methods.

Now the problem I have, is that I need a User for this DAO. But User is abstract and I do not make any User objects. I can make three different DAO's for each of the other classes but they would just do the same. Is there a clean way to do this ... .

Their maybe is a simple solution but I'm just not seeing it.

You can pass Admin, Moderator or Lector instances as parameters to your create method. Polymorphism in Java allows that kind of behaviour.

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