b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

微服务架构 云计算 重构 -改变既有代码的设计 ---- 笔记(15)

电脑杂谈  发布时间:2018-10-13 16:05:07  来源:网络整理

动机

静态类别检查

在一个类中拥有一个不变的类型码影响整个类的行为

使用子类来替代这个不变的类型码


    class Employee...
        private int _type;

        static final int ENGINEER = 0;
        static final int SALESMAN = 1;
        static final int MANAGER = 2;

        Employee (int type) {
            _type = type;
        }
    } 

to


    abstract int getType();
    static Employee create(int type) {
        switch (type) {
            case ENGINEER:
                return new Engineer();
            case SALESMAN:
                return new Salesman();
            case MANAGER:
                return new Manager();
            default:
                throw new IllegalArgumentException("Incorrect type code value");
        }
    }

动机

执行不同的代码逻辑取决于这个type的值

当每个type对象有着唯一的特征

应用于架构体

在类中有个类型码,并通过这个类型码来影响行为,但是你不能使用子类

通过状态对象来代替这个类型码


    class Employee {
        private int _type;

        static final int ENGINEER = 0;
        static final int SALESMAN = 1;
        static final int MANAGER = 2;

        Employee (int type) {
            _type = type;
        }
        int payAmount() {
            switch (_type) {
                case ENGINEER:
                    return _monthlySalary;
                case SALESMAN:
                    return _monthlySalary + _commission;
                case MANAGER:
                    return _monthlySalary + _bonus;
                default:
                    throw new RuntimeException("Incorrect Employee");
                }
            }
        }
    }

to


    class Employee...
        static final int ENGINEER = 0;
        static final int SALESMAN = 1;
        static final int MANAGER = 2;

        void setType(int arg) {
            _type = EmployeeType.newType(arg);
        }
        class EmployeeType...
            static EmployeeType newType(int code) {
                switch (code) {
                    case ENGINEER:
                        return new Engineer();
                    case SALESMAN:
                        return new Salesman();
                    case MANAGER:
                        return new Manager();
                    default:
                        throw new IllegalArgumentException("Incorrect Employee Code");
                }
            }
        }
        int payAmount() {
            switch (getType()) {
                case EmployeeType.ENGINEER:
                    return _monthlySalary;
                case EmployeeType.SALESMAN:
                    return _monthlySalary + _commission;
                case EmployeeType.MANAGER:
                    return _monthlySalary + _bonus;
                default:
                    throw new RuntimeException("Incorrect Employee");
            }
        }
    }


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-89441-15.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...