Remember a failed attempt to apply the Observer pattern in your project

I learned the observer pattern and want to try it out when I rewrite the project recently.

The scenario is as follows. There is a contract amount in the object project (Project), which may be updated after the first filling. At this time, the Estimate and the budget table should be updated. It is said that there is no need to use design patterns for this simple and specific requirement, just try to use it hard.

First of all, determine the observer Observer and the observed Subject. The initial observer is Estimate, and the observed subject is Project. Later, it is found that it is more suitable to set the Service layer. Project can be passed as a specific State variable, which is a bit like the previous one. Status mode.

Because the Observable provided by jdk is a concrete class, it must be inherited before it can be used. In this case, you can only write it yourself. Instead, use the naming method of listener and define the interface first.

public interface ProjectListener {
    public void onProjectChanged(Project project);
}

Then write the observer and related registration, removal, notification methods in ProjectService

private List<ProjectListener> listeners = Lists.newArrayList();

public void registerProjectListener(ProjectListener projectListener) {
   listeners.add(projectListener);
}

public void unregisterProjectListener(ProjectListener projectListener) {
   listeners.remove(projectListener);
}

public void notifyAllListener(Project project) {
   for (ProjectListener projectListener:listeners) {
      projectListener.onProjectChanged(project);
   }
}

Next, I was dumbfounded. When to register the Listener, the book is in the main method. At the beginning, the registration method is called to register once. Now put it in the mvc system, when to register, it stands to reason that the container can be registered when it is initialized, but I don't know where to write in the application

If you don't think about this first, keep reading

projectService.registerProjectListener(new ProjectListener() {
         @Override
         public void onProjectChanged (Project p) {
            //The corresponding estimate should be obtained and updated here, but the question is, how to inject the Service in the anonymous class
               estimateService.getByProjectId (p.getId ());
            
               estimateService.update (estimate);
         }
      });
 
   }

Stuck on injection again. . It may feel that it is really not suitable for such "hard" use

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325711721&siteId=291194637