Analysis of the observer mode in the file path Monitoring Project

Source: Internet
Author: User
1. Overview

The observer pattern is a software design pattern that describes how to establish dependencies between objects and how to construct systems that meet such requirements. In this mode, the key object is to observe the target and the observer. A target can have any number of dependent observers. Once the status of the target changes, all observers will be notified. As a response to this notification, each observer immediately updates his or her status to synchronize with the target status. This interaction is also called publish-subscribe ). The target is the publisher of the notification. It does not need to know who is its observer when sending the notification. It can have any number of observers subscribe to it and receive the notification.

This mode includes four roles:

  • Abstract observer role: This is an abstract topic. It stores all references to the observer object in a collection, and each topic can have any number of observers. Abstract topic provides an interface to add and delete observer roles. It is generally implemented using an abstract class and interface.
  • Abstract observer role: Defines an interface for all specific observers and updates themselves when receiving topic notifications.
  • Specific observer role: This is a specific topic. When the internal status of a group topic changes, all registered observers send a notification.
  • Specific observer role: Implements the update interface required by the abstract observer role, while aligning its status with the drawing status.

Observer mode structure

2. Implementation

Abstract observer:

package directoryobserver;import org.apache.commons.io.*;import org.apache.commons.io.filefilter.*;import org.apache.commons.io.monitor.*;import org.apache.log4j.*;import java.io.*;public class DirectoryObserver{    private final IOFileFilter doneFileFilter;    private FileAlterationObserver observer;    private Logger log = Logger.getLogger(DirectoryObserver.class);    private File directory;    static boolean isStarting = false;    public DirectoryObserver(File directory)    {        this.directory = directory;        doneFileFilter = FileFilterUtils.suffixFileFilter(".done");        observer = new FileAlterationObserver(directory, doneFileFilter);    }        public void addListener(NewFileListener listener)    {        observer.addListener(new DoneFileAlterationListener(listener));    }        public void start() throws Exception    {        FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);        isStarting = true;        monitor.start();        log.info("Watching for new files...");        for (FileAlterationListener listener : observer.getListeners())        {            for (File doneFile : FileUtils.listFiles(directory, doneFileFilter, FileFilterUtils.directoryFileFilter()))            {                listener.onFileCreate(doneFile);            }        }        isStarting = false;    }}

Specific observer:

package directoryobserver;import org.apache.commons.codec.digest.*;import org.apache.commons.io.monitor.*;import org.apache.log4j.*;import java.io.*;final class DoneFileAlterationListener implements FileAlterationListener{    private final NewFileListener newFileListener;    private Logger log = Logger.getLogger(DoneFileAlterationListener.class);        public DoneFileAlterationListener(NewFileListener newFileListener)    {        this.newFileListener = newFileListener;    }        @Override    public void onStop(FileAlterationObserver observer)    {    }    @Override    public void onStart(FileAlterationObserver observer)    {    }    @Override    public void onFileDelete(File file)    {    }    @Override    public void onFileCreate(File doneFile)    {        try        {            log.info("Received done file " + doneFile.getName());            if(doneFile.exists())            {                String[] tokens = doneFile.getName().split("\\.");                if (tokens.length != 3)                {                    newFileListener.onError(doneFile, new WrongDoneFileName());                    return;                }                String name = tokens[0];                String md5 = tokens[1];                File newFile = new File(doneFile.getParent() + File.separator + name);                String calculatedMd5 = DigestUtils.md5Hex(new FileInputStream(newFile));                if (calculatedMd5.equals(md5))                {                    newFileListener.onNewFile(newFile);                }                else                {                    newFileListener.onChecksumMismatch(newFile, doneFile);                }            }            else if(!DirectoryObserver.isStarting)            {                newFileListener.onError(doneFile, new DoneFileException());            }        }        catch (Exception e)        {            newFileListener.onError(doneFile, e);        }        finally        {            doneFile.delete();        }    }    @Override    public void onFileChange(File file)    {    }    @Override    public void onDirectoryDelete(File directory)    {    }    @Override    public void onDirectoryCreate(File directory)    {    }    @Override    public void onDirectoryChange(File directory)    {    }}

The observer observes the file in the path. When the file changes, the observer can be notified and perform corresponding operations.

3. Effect
  • The presentation layer and data logic layer can be separated, and a stable message update transfer mechanism is defined. The update interface is abstracted so that different presentation layers can be used as specific observer roles.
  • Establishes an abstract coupling between the observed object and the observer.
  • Supports broadcast communication.
  • Meets the requirements of the "Open and closed principle.

Analysis of the observer mode in the file path Monitoring Project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.