码迷,mamicode.com
首页 > 其他好文 > 详细

责任链模式

时间:2019-04-11 19:48:21      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:end   out   责任链   code   oss   ring   sso   info   override   

技术图片

/**
 * 处理价格折扣的抽象类
 */
public abstract class PriceHandler {
     // 直接后继,用于传递请求
     protected PriceHandler successor;
     public void setSuccessor(PriceHandler successor) {
          this.successor = successor;
     }
     // 处理折扣请求
     public abstract void processDicount(float discount);
}

public class Sales extends PriceHandler {
     @Override
     public void processDicount(float discount) {
          if(discount <= 0.1) {
               System.out.format("%s批准了折扣:%.2f%n", this.getClass().getName(), discount);
          } else {
               successor.processDicount(discount);
          }
     }
}

public class Manager extends PriceHandler{
     @Override
     public void processDicount(float discount) {
          if(discount <= 0.3) {
               System.out.format("%s批准了折扣:%.2f%n", this.getClass().getName(), discount);
          } else {
               successor.processDicount(discount);
          }
     }
}

public class Boss extends PriceHandler {
     @Override
     public void processDicount(float discount) {
          if(discount <= 0.5) {
               System.out.format("%s批准了折扣:%.2f%n", this.getClass().getName(), discount);
          } else {
               System.out.format("%s拒绝了折扣:%.2f%n", this.getClass().getName(), discount);
          }
     }
}

/**
 * 创建PriceHandler的工厂类
 */
public class PriceHandlerFactory {
     public static PriceHandler createHandler() {
          PriceHandler sale = new Sales();
          PriceHandler manager = new Manager();
          PriceHandler boss = new Boss();
          sale.setSuccessor(manager);
          manager.setSuccessor(boss);
          return sale;
     }
}

public class Customer {
     private PriceHandler priceHandler;
     public Customer(PriceHandler priceHandler) {
          this.priceHandler = priceHandler;
     }

     public void requestDiscount(float discount) {
          priceHandler.processDicount(discount);
     }

     public static void main(String[] args) {
          Customer c = new Customer(PriceHandlerFactory.createHandler());
          for(int i=1;i<=10;i++) {
               System.out.print(i + ":");
               c.requestDiscount(new Random().nextFloat());
          }
     }
}

责任链模式

标签:end   out   责任链   code   oss   ring   sso   info   override   

原文地址:https://www.cnblogs.com/mabaoqing/p/10691609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!