Chain of responsibility

public class Handler {
    private Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public Handler getSuccessor() {
        return successor;
    }

    public void handleRequest(char c) {
        if(successor != null)
            successor.handleRequest(c);
    }
}

 

 

public class NumberHandler extends Handler {
    public void handleRequest(char c) {
        if(Character.isDigit(c)) {
            System.out.println("Number has been handled");
        }
        else {
            getSuccessor().handleRequest(c);
        }
    }
}

 

public class CharacterHandler extends Handler {
    public void handleRequest(char c) {
        if(Character.isLetter(c)) {
            System.out.println("Character has been handled");
        }
        else {
            getSuccessor().handleRequest(c);
        }
    }
}

 

public class SymbolHandler extends Handler {
    public void handleRequest(char c) {
        System.out.println("Symbol has been handled");
    }
}

 

import java.io.*;

public class Application {
    public static void main(String[] args)
                                 throws IOException {
        Handler numberHandler = new NumberHandler();
        Handler characterHandler = new CharacterHandler();
        Handler symbolHandler = new SymbolHandler();

        numberHandler.setSuccessor(characterHandler);
        characterHandler.setSuccessor(symbolHandler);

        System.out.print("Press any key then return: ");
        char c = (char)System.in.read();
        numberHandler.handleRequest(c);
    }

 

 

 

你可能感兴趣的:(chain)