zoukankan      html  css  js  c++  java
  • 每日一个设计模式之策略模式

    场景:饭店收银,1现金,2刷卡,3微信

    首先定一个收费的接口

    public interface ShouFei {
        /**
         * 收费
         */
        void shoufei();
    }

    有接口就有实现类:下面3个实现类

    public class XianJIn implements ShouFei {
    
        @Override
        public void shoufei() {
            System.out.println("现金支付");
            
        }
    
    }
    public class ShuaKa implements ShouFei {
    
        @Override
        public void shoufei() {
            System.out.println("刷卡支付");
            
        }
    
    }
    public class WeiXin implements ShouFei {
    
        @Override
        public void shoufei() {
            System.out.println("微信支付");
            
        }
    
    }

    接下来定一个类用于封装这个收费

    public class FuKuan {
        ShouFei shouFei;
    
        public FuKuan(ShouFei shouFei) {
            this.shouFei = shouFei;
        }
    
        public void shouFei() {
            shouFei.shoufei();
        }
    
    }

    接下来是主方法

    public class Qiantai {
        public static void main(String[] args) {
            shoufei(1);
            shoufei(2);
            shoufei(3);
        }
    
        /**
         * 1,现金,2刷卡,3微信
         * 
         * @param type
         */
        public static void shoufei(int type) {
            FuKuan fuKuan = null;
            if (type == 1) {
                fuKuan = new FuKuan(new XianJIn());
            } else if (type == 2) {
                fuKuan = new FuKuan(new ShuaKa());
            } else if (type == 3) {
                fuKuan = new FuKuan(new WeiXin());
            }
    
            fuKuan.shouFei();
        }
    }

    这样,我只需要在处理我的逻辑的时候知道支付的类型就调用不同的方法,扩展的时候只需要添加一个实现类和在主方法的收费这个方法里添加一个类型就可以了.

  • 相关阅读:
    【每日日报】第四十六天
    jsp动作标识
    JSP注释
    request对象
    Servlet的创建和配置
    基于图书管理系统的浏览
    在JSP中应用JavaBean
    交流会
    基于图书管理系统的改
    基于图书管理系统的增
  • 原文地址:https://www.cnblogs.com/songfahzun/p/6025320.html
Copyright © 2011-2022 走看看