Chain of Responsibility Pattern

Chain of Repository: giống như servlet filters, mỗi khi có request sẽ chạy qua tất cả Filters.
Hiện thưc Chain: giống như liên kết đơn, mỗi khi có Filter nào handle request đó sẽ dừng.

Code chỉ là ý tưởng, mình viết trên giấy nên chắc là ko run dc😀

public class App {
public static void main(String[] args) {
OrcKing king = new OrcKing();
king.makeRequest(new Request(RequestType.A, "go to supuermaker"));
king.makeRequest(new Request(RequestType.B, "go to Ha Long"));
king.makeRequest(new Request(RequestType.C, "come back"));

}
}

public class OrcKing {

private RequestHandler chain;    // abstract, node

public OrcKing() {
buildChain();
}

// get, set chain

public void buildChain() {
chain = new OrcCommander(new orcOfficer(new orcSoldier(null))));
}

public void makeRequest(Request request) {
chan.handleRequest(request);
}

}

public Abstract RequestHandler() {
private RequestHandler next;

public RequestHandler(RequestHandler handler) {
this.next = handler;
}

public void handleRequest(Request request) {
if (this.next != null) {
this.next.handleRequest(request);
}
}
}

public class orcCommander extends RequestHandler {

public orcCommander(RequestHandler handler) {
super(handler);
}

@Override
public void handleRequest(Request req) {
if (req.getType == A) {
// bla bla bla
request.markHanlded();
return;
}
super.handleRequest(req);
}

}

One thought on “Chain of Responsibility Pattern

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s