描述
責任鏈模式(CoR)建議發出請求的對象與可能處理這個請求的對象集合之間是低耦合的(set of potential request handler objects)
在有不止一個對象可以處理或實現(fulfill)客戶請求的時候
給下一個對象
例如
當C收到請求時
下面是責任鏈模式(CoR)一些重要的特征
(
(
(
(
例子
讓我們模擬一個在特定組織裡的購買請求(PR)授權過程的應用
Table
Management Level Authorization Limit
Branch Manager $
Regional Director $
Vice President $
President and COO $
我們可以定義不同的類
Listing
class BranchManager {
static double LIMIT =
…
…
}//End of class
class RegionalDirector {
static double LIMIT =
…
…
}//End of class
class VicePresident {
static double LIMIT =
…
…
}//End of class
class PresidentCOO {
static double LIMIT =
…
…
}//End of class
讓我們定義一個PurchaseRequest類
PurchaseRequest
ID:int
description:String
amount:double
getAmount():double
Figure
Listing
class PurchaseRequest {
private int ID;
private String description;
private double amount;
public PurchaseRequest(int id
ID = id;
description = desc;
amount = amt;
}
public double getAmount() {
return amount;
}
public String toString() {
return ID +
}
}
一個給定的購買請求(PR)被上面的管理代表所授權或處理
利用責任鏈模式(CoR)
Listing
public abstract class PRHandler {
private PRHandler nextHandler;
private String handlerName;
public PRHandler(String name) {
handlerName = name;
}
public String getName() {
return handlerName;
}
public abstract boolean authorize(PurchaseRequest request);
public PRHandler getNextHandler() {
return nextHandler;
}
public void setNextHandler(PRHandler handler) {
nextHandler = handler;
};
}
Figure
現在
Listing
class BranchManager extends PRHandler {
static double LIMIT =
public BranchManager(String name) {
super(name);
}
public boolean authorize(PurchaseRequest request) {
double amount = request
if (amount <= LIMIT) {
System
return true;
} else {
//forward the request to the next handler
return getNextHandler()
}
}
}//End of class
class RegionalDirector extends PRHandler {
static double LIMIT =
public RegionalDirector(String name) {
super(name);
}
public boolean authorize(PurchaseRequest request) {
double amount = request
if (amount <= LIMIT) {
System
request);
return true;
} else {
//forward the request to the next handler
return getNextHandler()
}
}
}//End of class
class VicePresident extends PRHandler {
static double LIMIT =
public VicePresident(String name) {
super(name);
}
public boolean authorize(PurchaseRequest request) {
double amount = request
if (amount <= LIMIT) {
System
return true;
} else {
//forward the request to the next handler
return getNextHandler()
}
}
}//End of class
class PresidentCOO extends PRHandler {
static double LIMIT =
public PresidentCOO(String name) {
super(name);
}
public boolean authorize(PurchaseRequest request) {
double amount = request
if (amount <= LIMIT) {
System
return true;
} else {
System
return false;
}
}
}//End of class
為了授權購買請求
(
Figure
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27453.html