简体   繁体   中英

Email using Singleton pattern

I have a webapp running on my server, which does some balance update. Once the balance is updated, I need to check if the balance is below 5000. In case, the balance goes below 5000, I should send an email alert . The point to note here is that, I need to send the alert only once in a day , alert should not keep going every time the balance is below 5000. I believe, I should use singleton pattern for sending the mail, but I am not sure how to use this. The program when sees the balance going below 5000, should call the singleton class which will have the function to send email alert, but how do you ensure that program will not call this function again when the balance goes down? Can anyone guide me on this?

singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

But for your requirement I don't know may it will help. Perhaps you can use some flag concept. And flag should be cleared every day.

Singleton is a design pattern that makes sure only one instance of an object is created.

Doesn't sound like it has anything to do with what you need, you could add a flag in your DB like alert_sent=true/false and update it accordingly.

You do not need any "special" design patterns here. For instance you can store the date when the last email notification was sent, like:

Date lastEmail = ... // last email date

And when trying to send email chekc the condition:

If( ... ) // lastEmail is before current day
{  //send emal and update lastEmail }

There is two separate things you need think about:

  • Email sending service.

Several ways to implement it. Yes, it could be Singleton , but it also could be a plain Java service. If you use Spring , then they have very simple and useful predefined implementations. Here is an example .

  • Your checking balance logic.

Depends on what you really need. If you need to check every balance update but send alerts not more that once per day, then it will be something like:

    private Date lastAlertDate;

    private static final BALANCE_LIMIT = 5000;

    private void handleBalanceUpdated(long balance) {
        if (balance < 5000) {
        log.info("Balance has gone below {}", BALANCE_LIMIT);
        int daysDifference = getDifferenceInDays(lastAlertDate, new Date());
        if (daysDifference >= 1) {
            log.info("Last alert was {} days ago, going to send email alert", daysDifference);
            alertService.sendSimpleAlert("Balance has gone below " + BALANCE_LIMIT + "!");
            lastAlertDate = new Date();
        }
    }
    }

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