package design.pattern.behavioral;
import design.pattern.behavioral.ChainOfResponsibility.*;
public class ChainOfResponsibility {
public static class Chain {
private Request[] requests = null;
private Handler[] handlers = null;
public Chain(Handler[] handlers, Request[] requests){
this.handlers = handlers;
this.requests = requests;
}
public void start() {
for(Request r : requests)
for (Handler h : handlers)
if(h.handle(r)) break;
}
}
public static class Request {
private int value;
public Request setValue(int value){
this.value = value;
return this;
}
public int getValue() {
return value;
}
}
public static class Handler<T> {
private Command<T> command = null;
public Handler(Command<T> command) {
this.command = command;
}
public boolean handle(T request) {
return command.execute(request);
}
}
public static abstract class Command<T>{
public abstract Boolean execute(T request);
}
}
class TestChainOfResponsibility {
public static void main(String[] args) {
new TestChainOfResponsibility().test();
}
private void test() {
new Chain(new Handler[]{ // chain of responsibility
new Handler<Request>(
new Command<Request>(){ // command
public Boolean execute(Request condition) {
boolean result = condition.getValue() >= 600;
if (result) System.out.println("You are rich: " + condition.getValue() + " (id: " + condition.hashCode() + ")");
return result;
}
}
),
new Handler<Request>(
new Command<Request>(){
public Boolean execute(Request condition) {
boolean result = condition.getValue() >= 100;
if(result) System.out.println("You are poor: " + condition.getValue() + " (id: " + condition.hashCode() + ")");
return result;
}
}
),
},
new Request[]{
new Request().setValue(600), // chaining method
new Request().setValue(100),
}
).start();
}
}
最佳答案
对于这样一个笼统的问题,我认为没有有意义的答案。设计模式不是孤立存在的,也没有“完美的形式”:它们存在于上下文中。
A pattern is a solution to a problem in a context.
因此,在不知道您的解决方案的上下文的情况下,我们对此无话可说。你试图用它解决的具体问题是什么?什么力量在起作用?你的限制是什么?您对当前的解决方案有任何问题吗?如果您提供有关这些的更多详细信息,也许我们可以给出更好的答案。
关于java - 在此责任链的 java 实现中,您想更正和/或改进什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3048272/