public class TestResponsibility {
public static void main(String[] args) {
Context context=new Context();
RuleHandler newUserRuleHandler=new NewUserRuleHandler();
RuleHandler locationRuleHandler=new LocationRuleHandler();
LimitRuleHandler limitRuleHandler = new LimitRuleHandler();
newUserRuleHandler.setSuccessor(locationRuleHandler);
limitRuleHandler.setSuccessor(newUserRuleHandler);
limitRuleHandler.apply(context);
}
}
public abstract class RuleHandler {
protected RuleHandler successor;
public abstract void apply(Context context);
public void setSuccessor(RuleHandler successor) {
this.successor = successor;
}
public RuleHandler getSuccessor() {
return successor;
}
}
public class Context {
public boolean isNewUser(){
return true;
}
public boolean isSupportedLocation(){
return false;
}
public boolean queryRemainedTimes(){
return true;
}
}
public class LimitRuleHandler extends RuleHandler{
@Override
public void apply(Context context) {
if(context.queryRemainedTimes()){
System.out.println("还是有奖品");
if(this.getSuccessor()!=null){
this.getSuccessor().apply(context);
}
}else{
System.out.println("已经没有奖品");
}
}
}
public class LocationRuleHandler extends RuleHandler{
@Override
public void apply(Context context) {
if(context.isSupportedLocation()){
System.out.println("这是本地用户");
if(this.getSuccessor()!=null){
this.getSuccessor().apply(context);
}
}else{
System.out.println("这不是本地用户");
}
}
}
public class NewUserRuleHandler extends RuleHandler {
@Override
public void apply(Context context) {
if(context.isNewUser()){
System.out.println("这是用户");
if (this.getSuccessor() != null) {
this.getSuccessor().apply(context);
}
}else{
System.out.println("这不是用户");
}
}
}