티스토리 뷰

CoR02.zip



# Handler.java


import java.util.ArrayList;


public abstract class Handler {

    Handler nextHandler;

    

    protected void setNextHandler(Handler handler) {

this.nextHandler = handler;

    }

  

    protected void setNextHandlers(ArrayList<Handler> handlers) {

for (int i = 0; i < handlers.size() - 1; i++) {

   handlers.get(i).setNextHandler(handlers.get(i + 1));

}

    }

    

    abstract void checkRequest(Request request);

}



# Request.java


public class Request {

    private int requestValue = 0;


    public int getRequestValue() {

if (this.requestValue < 0) {

   this.requestValue = -this.requestValue;

}

        return this.requestValue;

    }


    public void setRequestValue(int requestValue) {

        this.requestValue = requestValue;

    }

}



# CheckEven.java


public class CheckEven extends Handler {


    @Override

    void checkRequest(Request request) {

int requested = request.getRequestValue();

if (requested > 0 && requested % 2 == 0) {

   System.out.println("[" + requested + "] is even");

} else {

   nextHandler.checkRequest(request);

}

    }

}



# CheckOdd.java


public class CheckOdd extends Handler {


    @Override

    void checkRequest(Request request) {

int requested = request.getRequestValue();

if (requested > 0 && requested % 2 != 0) {

   System.out.println("[" + requested + "] is odd");

} else {

   nextHandler.checkRequest(request);

}

    }

}



# CheckZero.java


public class CheckZero extends Handler {


    @Override

    void checkRequest(Request request) {

int requested = request.getRequestValue();

if (requested == 0) {

   System.out.println("[" + requested + "] is zero");

} else {

   nextHandler.checkRequest(request);

}

    }

}



# Main.java


import java.util.ArrayList;


public class Main {


    public static void main(String[] args) {

Request request = new Request();

CheckEven checkEven = new CheckEven();

CheckOdd checkOdd = new CheckOdd();

CheckZero checkZero = new CheckZero();

ArrayList<Handler> handlers = new ArrayList<>();

handlers.add(checkEven);

handlers.add(checkOdd);

handlers.add(checkZero);

handlers.get(0).setNextHandlers(handlers);

handlers.get(0).checkRequest(request);

request.setRequestValue(-21);

handlers.get(0).checkRequest(request);

request.setRequestValue(-2);

handlers.get(0).checkRequest(request);

    }

}



# 결과


[0] is zero

[21] is odd

[2] is even



댓글
댓글쓰기 폼
공지사항
Total
394,929
Today
0
Yesterday
28
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함