zoukankan      html  css  js  c++  java
  • 一个使用enum实现多态的例子

    下面的写法与直接 使用静态方法而言,可读性、可维护性更强
    是不是有DSL的感觉....

    当然enum反编译后,的确就是静态方法。

    /**
     * Created by MyWorld on 2016/8/3.
     */
    public enum Operation {
        PLUS("+") {
            @Override
            public int apply(int x, int y) {
                return x + y;
            }
        }, MINUS("-") {
            @Override
            public int apply(int x, int y) {
                return x - y;
            }
        }, TIMES("*") {
            @Override
            public int apply(int x, int y) {
                return x * y;
            }
        }, DIVIDE("/") {
            @Override
            public int apply(int x, int y) {
                return x / y;
            }
        };
    
        private String op;
    
        Operation(String op) {
            this.op = op;
        }
    
        public abstract int apply(int x, int y);
    
        public String getOp() {
            return op;
        }
    
        public void setOp(String op) {
            this.op = op;
        }
    
        public static void main(String[] args) {
            System.out.println(Operation.PLUS.apply(1, 2));
        }
    
    }

    感谢刘光聪在简书上的分享

  • 相关阅读:
    angularjs $index用来取顺序
    angularjs &登录跳转
    if(!confirm("您确定删除吗?")){return;}
    登录跳转
    undefined null测试
    git生成密钥
    遍历map
    网络相关名词解释
    redis的Pub/Sub
    SQLAlchemy的使用
  • 原文地址:https://www.cnblogs.com/softidea/p/5734862.html
Copyright © 2011-2022 走看看