简体   繁体   English

抽象类 - 扩展类和DAO

[英]Abstract class - extended classes and DAO

I have a abstract class User and 3 classes who extend from this class (Admin, Modurator, Lector). 我有一个抽象类User和3个类,它们从这个类扩展(Admin,Modurator,Lector)。

In my db I have a table User with the data needed (UserName / Password / Security_lvl). 在我的数据库中,我有一个表用户所需的数据(UserName / Password / Security_lvl)。

The connection to the database for User I do with DAO. 用户的数据库连接我用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. 在java中,根据用户类型我制作特定的Admin,Modurator或Lector对象,以便我可以使用他们的特定方法。

Now the problem I have, is that I need a User for this DAO. 现在我遇到的问题是,我需要这个DAO的用户。 But User is abstract and I do not make any User objects. 但是User是抽象的,我不做任何User对象。 I can make three different DAO's for each of the other classes but they would just do the same. 我可以为其他每个类制作三个不同的DAO,但他们也会这样做。 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. 您可以将Admin,Moderator或Lector实例作为参数传递给create方法。 Polymorphism in Java allows that kind of behaviour. Java中的多态性允许这种行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM