UML
uml
代码示例
创建一个接口
public abstract class KaiDanHandler {
/**
* 持有后继的责任对象
*/
protected KaiDanHandler successor;
/**
* 传入参数的,根据具体需要来选择是否传递参数
*/
public abstract void handleRequest(Data data);
}
创建实现接口的实现类
public class JiNengHandler extends KaiDanHandler {
@Override
public void handleRequest(Data data) {
if (data.showJiNeng){
System.out.println("请去选择节能补贴的赠品");
}else {
if (null != successor){
successor.handleRequest(data);
}else {
System.out.println("现在正式开单");
}
}
}
}
public class YanbaoHandler extends KaiDanHandler {
@Override
public void handleRequest(Data data) {
if (data.showYanbao){
System.out.println("请去购买延保");
}else {
if (null != successor){
successor.handleRequest(data);
}else {
System.out.println("现在正式开单");
}
}
}
}
public class ZaiTuHandler extends KaiDanHandler {
@Override
public void handleRequest(Data data) {
if (data.showZaitu){
System.out.println("是否要取消所选在途的商品");
}else {
if (null != successor){
successor.handleRequest(data);
}else {
System.out.println("现在正式开单");
}
}
}
}
创建参数实体
public class Data {
public boolean showZaitu;
public boolean showYanbao;
public boolean showJiNeng;
}
模拟请求的客户端
public class Client {
private Data mData;
public static void main(String[] args) {
Client client = new Client();
client.mData = client.mockData();
//创建实现者对象
YanbaoHandler yanbaoHandler = new YanbaoHandler();
ZaiTuHandler zaiTuHandler = new ZaiTuHandler();
JiNengHandler jiNengHandler = new JiNengHandler();
//设置实现功能的下一任对象
yanbaoHandler.successor = zaiTuHandler;
zaiTuHandler.successor = jiNengHandler;
//发出命令请求
yanbaoHandler.handleRequest(client.mData);
}
private Data mockData(){
Data data = new Data();
data.showYanbao = true;
data.showZaitu = false;
data.showJiNeng = true;
return data;
}
}
网友评论