美文网首页
设计模式之责任链模式

设计模式之责任链模式

作者: smallstrong | 来源:发表于2017-04-28 15:25 被阅读20次

责任链模式

责任链模式UML.png
abstract class Department{
    protected Department mDepartment;
    


    public void setDepartment(Department department){
        this.mDepartment = department;
    }
    
    public abstract void makeChoice(Things s);
}

抽象部门,成员变量指定上级部门,定义处理事情的方法

class Municipal extends Department{
    public void makeChoice(Things s){
        if(s.level <= 1){
            Log.i("smallstrong","市级部门"+s.thing);
        }else{
            this.mDepartment.makeChoice(s);//报告上级
        }
    }
}

市级部门

class Provincial extends Department{
    public void makeChoice(Things s){
        if(s.level <= 2){
            Log.i("smallstrong","省级部门"+s.thing);
        }else{
            this.mDepartment.makeChoice(s);//报告上级
        }
    }
}

省级部门

class Country extends Department{
    public void makeChoice(Things s){
        if(s.level > 0){
            Log.i("smallstrong","国家级部门"+s.thing);
        }else{
            //this.mDepartment.makeChoice(s);//报告上级
        }
    }
}   

国家级部门

class Things{
    private static final int level;//1  市级范围  2 省级范围 3 国家级范围
    private static final String thing;
    
    public Things(int level ,String thing){
        this.level = level;
        this.thing = thing;
    }
}

具体事情与等级

class Client{
    public static void main(String args[]){
        Department mMunicipal,mProvincial,mCountry;
        mMunicipal = new Municipal();
        mProvincial = new Provincial();
        mCountry = new Country();
        mMunicipal.setDepartment(mProvincial);
        mProvincial.setDepartment(mCountry);
        
        Things thing = new Things(1,"李达康冲击GDP");
        mMunicipal.makeChoice(thing);   
        
        Things thing = new Things(2,"沙瑞金书记召开省部级会议");
        mMunicipal.makeChoice(thing);   
        
        Things thing = new Things(3,"赵立春老书记被罢免");
        mMunicipal.makeChoice(thing);   
    }
}

客户端,先要构造一个责任顺序。

log如下

[市级部门李达康冲击GDP]

[沙瑞金书记召开省部级会议]

[赵立春老书记被罢免]

个人总结

责任链模式适用于多个对象都可以处理一个事情,对象可以根据情况处理或者丢给一个级别的对象处理。客户端要代码实现一个责任顺序。Android中view事件的分发已经有序广播的传递都采用了这种模式(相似)。

![责任链模式UML.png](https://img.haomeiwen.com/i1321838/c15b8bef266c5639.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

相关文章

网友评论

      本文标题:设计模式之责任链模式

      本文链接:https://www.haomeiwen.com/subject/ygxazttx.html