设计模式——责任链模式

//定义接口

public interface Handler {
     public void operate();
}


//

public class Myhandler implements Handler{
     private String name;
     private Handler handler;
    
     public Myhandler(String name) {
         super();
         this.name = name;
     }


     public Myhandler(String name, Handler handler) {
         super();
         this.name = name;
         this.handler = handler;
     }
    

    public String getName() {
         return name;
     }

    public void setName(String name) {
         this.name = name;
     }

    public Handler getHandler() {
         return handler;
     }

    public void setHandler(Handler handler) {
         this.handler = handler;
     }

    @Override
     public void operate() {
         // TODO Auto-generated method stub
         if (getHandler()!=null) {
             getHandler().operate();
         }
         System.out.println(name+"deal!");
     }
    
}

public static void main(String[] args) {
     Myhandler myhandler = new Myhandler("A");
     Myhandler myhandler1 = new Myhandler("B");
     Myhandler myhandler2 = new Myhandler("C");
     myhandler.setHandler(myhandler1);
     myhandler1.setHandler(myhandler2);
     myhandler.operate();
    
}

posted @ 2020-03-25 18:33  小海_macro  阅读(80)  评论(0编辑  收藏  举报