Java-observer mode business practice

Java-observer mode business practice

introduction

Observer mode is a commonly used design pattern, which defines a one-to-many dependency relationship, allowing multiple observer objects to monitor a subject object at the same time. The subject object notifies all observer objects of state changes, enabling them to update themselves automatically.

In the user registration scenario, when a user completes registration, there are usually multiple operations that need to be performed, such as sending welcome emails, recording logs, updating databases, and so on. This scenario is very suitable for using the observer pattern, and these operations can be regarded as observers who register events. In this way, non-intrusive iteration can be achieved for subsequent maintenance or new business points.

practice

Define an Subjectinterface and a Observerinterface.

// Subject 接口
public interface Subject {
    
    
  // 注册观察者
  void registerObserver(Observer o);
	// 移除观察者	
  void removeObserver(Observer o);
  // 通知
  void notifyObservers();
}

// Observer 接口
public interface Observer {
    
    
    void update(String message);
}

Create a UserRegistrationclass that implements Subjectthe interface.

import java.util.ArrayList;

// UserRegistration 类
public class UserRegistration implements Subject {
    
    

    private ArrayList<Observer> observers;
    private String message;

    public UserRegistration() {
    
    
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
    
    
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
    
    
        int i = observers.indexOf(o);
        if (i >= 0) {
    
    
            observers.remove(i);
        }
    }

    @Override
    public void notifyObservers() {
    
    
        for (int i = 0; i < observers.size(); i++) {
    
    
            Observer observer = (Observer)observers.get(i);
            observer.update(message);
        }
    }

    public void setMessage(String message) {
    
    
        this.message = message;
        notifyObservers();
    }
}

Next, create three specific observer classes, namely SendEmail, LogRecord, UpdateDatabase, which implement Observerthe interface respectively.

// SendEmail 类
public class SendEmail implements Observer {
    
    

    private Subject userRegistration;

    public SendEmail(Subject userRegistration) {
    
    
        this.userRegistration = userRegistration;
        userRegistration.registerObserver(this);
    }

    @Override
    public void update(String message) {
    
    
        System.out.println("Send Email: " + message);
    }
}

// LogRecord 类
public class LogRecord implements Observer {
    
    

    private Subject userRegistration;

    public LogRecord(Subject userRegistration) {
    
    
        this.userRegistration = userRegistration;
        userRegistration.registerObserver(this);
    }

    @Override
    public void update(String message) {
    
    
        System.out.println("Record Log: " + message);
    }
}

// UpdateDatabase 类
public class UpdateDatabase implements Observer {
    
    

    private Subject userRegistration;

    public UpdateDatabase(Subject userRegistration) {
    
    
        this.userRegistration = userRegistration;
        userRegistration.registerObserver(this);
    }

    @Override
    public void update(String message) {
    
    
        System.out.println("Update Database: " + message);
    }
}

test code

// Main 类
public class Main {
    
    

    public static void main(String[] args) {
    
    

        // 创建一个 UserRegistration 对象
        UserRegistration userRegistration = new UserRegistration();

        // 创建三个观察者对象
        SendEmail sendEmail = new SendEmail(userRegistration);
        LogRecord logRecord = new LogRecord(userRegistration);
        UpdateDatabase updateDatabase = new UpdateDatabase(userRegistration);

        // 模拟用户注册
        userRegistration.setMessage("A new user has registered.");

        // 移除一个观察者
        userRegistration.removeObserver(sendEmail);

        // 模拟另一个用户注册
        userRegistration.setMessage("Another user has registered.");
    }
}

output

Send Email: A new user has registered.
Record Log: A new user has registered.
Update Database: A new user has registered.
Record Log: Another user has registered.
Update Database: Another user has registered.

As you can see, when a user registers, emails are automatically sent, logs are recorded, and the database is updated. When another user signs up, SendEmailno more emails will be sent since the observer has been removed, but logging and updating the database will continue.

Summarize

The Observer pattern is a very practical design pattern, which can help us simplify the code and improve the scalability of the code in the user registration scenario. When you need to add, modify or remove an operation, you only need to add, modify or remove the corresponding observer without modifying other codes.

In actual application, the business may change, but the idea remains the same.

Supongo que te gusta

Origin blog.csdn.net/Arhhhhhhh/article/details/132626054
Recomendado
Clasificación