简体   繁体   English

当我将 function 分配给它时,如何自行更新变量

[英]How do I have a variable update itself when I assign a function to it

So I am trying to update a variable by just using a function call without changing it.所以我试图通过仅使用 function 调用而不更改它来更新变量。 So I want to have an object with a variable 'name' which will receive it's value from fetching it from a database:所以我想要一个带有变量“名称”的 object,它将从数据库中获取它的值:

String name = fetchNameFromDB(); // Name is 'Jim'

Then if I change the value in the database, whenever I refer to the 'name' value, it returns the updated value, example:然后,如果我更改数据库中的值,每当我引用“名称”值时,它都会返回更新后的值,例如:

String name = fetchNameFromDB(); // Assigns name as 'Jim'
changeNameTo("Steve"); // Changes the value in the database from 'Jim' to 'Steve'
System.out.println(name); // Will print 'Jim' but I want this to be printing 'Steve'

The only solution I have at the moment is this(I am using JDBC and MySQL):我目前唯一的解决方案是这个(我正在使用 JDBC 和 MySQL):

public  class GroundControlToMajorTom {
    static String theName;
    static String ID;

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        //System.out.println(returnEmployeeSalary("ivy"));
        theName = returnEmployeeName("72913");
        changeName("Kass", "72913");
        System.out.println(theName);
    }

    public static void changeName(String name, String ID) throws ClassNotFoundException, SQLException{
        System.out.println(theName);
        changeEmployeeName(name, ID);
        theName = returnEmployeeName(ID);
        System.out.println(theName);
    }

    public static void changeEmployeeName(String name, String ID) throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/sql_hr";
        String uname = "root";
        String pass = "Culley1max1";
        String query = "UPDATE employees SET first_name = '" + name + "' WHERE employee_ID = '" + ID + "'";

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, uname, pass);

        Statement st = con.createStatement();
        int rs = st.executeUpdate(query);

        st.close();
        con.close();
    }

    public static String returnEmployeeName(String ID) throws ClassNotFoundException {
        HashMap<String, String> infoHR = connectionInfoHR();

        String query = "SELECT first_name FROM employees WHERE employee_id = '" + ID + "'";

        Class.forName("com.mysql.cj.jdbc.Driver");

        try (Connection con = DriverManager.getConnection(infoHR.get("url"), infoHR.get("uname"), infoHR.get("pass"));
                Statement st = con.createStatement();
                ResultSet rs = st.executeQuery(query)) {

            rs.next();
            return rs.getString("first_name");

        } catch (Exception e) {
            return "ConnectionInfoHR credentials incorrect - Cannot connect to database";
        }
    }

Here I am manually reasigning the value every time through a separate function, how can I avoid this and have it fetch the value from the database and use the fetched value every time I call the variable name?在这里,我每次通过单独的 function 手动重新分配值,如何避免这种情况并让它从数据库中获取值并在每次调用变量名时使用获取的值?

I don't know why you want to do this, as other said it may be really a design issue.我不知道你为什么要这样做,因为其他人说这可能真的是一个设计问题。

Anyway, you may want to consider the idea to write custom events for your application.无论如何,您可能需要考虑为您的应用程序编写自定义事件的想法。 onValueChange() (for example) you could update the value inside your database assigning a function for each registered object to the event handler. onValueChange() (例如)您可以更新数据库中的值,为每个已注册的 object 分配一个 function 给事件处理程序。

One thing you can do is to design an interface, which satisfy your needs, having as first argument the target of the change and the function associated to the change.您可以做的一件事是设计一个满足您需求的接口,将更改的目标和与更改关联的 function 作为第一个参数。 In the end, on each change fired, your data would be updated automatically inside your database.最后,每次触发更改时,您的数据都会在数据库中自动更新。

You may want to look at some design patterns like Observer , Event Notifier or EventBus to use with this interface.您可能想查看一些设计模式,如ObserverEvent NotifierEventBus以与此接口一起使用。

IMPORTANT :重要
I do not recommend doing something like this, it has negative impacts on your application performance and I strongly advise against using it.我不建议这样做,它会对您的应用程序性能产生负面影响,我强烈建议不要使用它。

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

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