23.08.2017

Separation of interface from implementation

package my.home;

import java.util.ArrayList;
import java.util.Arrays;

interface Processor {
    String name();

    Object process(Object input);
}

public abstract class StringProcessor implements Processor {
    public static void main(String[] args) {
        String s = "The issue is that the HTTP request from the bank’s website and the request from the evil website are exactly the same";
        Apply.process(new Upcase(), s);
        Apply.process(new SplitterComparator(), s);
    }

    public String name() {
        return getClass().getSimpleName();
    }

    public abstract String process(Object input);
}

class SplitterComparator extends StringProcessor {
    @Override
    public String process(Object input) {
        ArrayList c = new ArrayList<>(Arrays.asList(((String) input).split(" ")));
        c.sort(String::compareTo);
        return c.toString();
    }
}

class Upcase extends StringProcessor {
    @Override
    public String process(Object input) {
        return ((String) input).toUpperCase();
    }

    @Override
    public String name() {
        return "new upcase";
    }
}

class Apply {
    static void process(Processor p, Object s) {
        System.out.println("Using processor:" + p.name());
        System.out.println(p.process(s));
    }
}
Output:
Using processor:new upcase
THE ISSUE IS THAT THE HTTP REQUEST FROM THE BANK’S WEBSITE AND THE REQUEST FROM THE EVIL WEBSITE ARE EXACTLY THE SAME
Using processor:SplitterComparator
[HTTP, The, and, are, bank’s, evil, exactly, from, from, is, issue, request, request, same, that, the, the, the, the, the, website, website]

Комментариев нет:

Отправить комментарий