重构-改善既有代码的设计(七):在对象之间搬移特性

1、搬移函数(Move Method)(1)症状:如果一个类有太多行为,或一个类与另一个类有太多合作而形成高度耦和(2)解决:在该函数最常引用的类中建立一个有着类似行为的新函数,将旧函数变成一个单纯的委托函数,或者是将旧函数完全移除(3)检查:调用端、被调用端、继承体系中任何一个重定义函数(4)如果源函数包含异常,需要判断逻辑上应该由哪个类来处理这一异常,如果应该由源类来负责,就把...
摘要由CSDN通过智能技术生成

1、搬移函数(Move Method)

(1)症状:如果一个类有太多行为,或一个类与另一个类有太多合作而形成高度耦和

(2)解决:在该函数最常引用的类中建立一个有着类似行为的新函数,将旧函数变成一个单纯的委托函数,或者是将旧函数完全移除

(3)检查:调用端、被调用端、继承体系中任何一个重定义函数

(4)如果源函数包含异常,需要判断逻辑上应该由哪个类来处理这一异常,如果应该由源类来负责,就把异常留在原地

(5)可以删除源函数,或将它当作一个委托函数保留下来

(6)如果要移除源函数,请将源类中对源函数的所有调用都替换成对目标函数的调用

//某银行系统中包含一个银行账户类BankAccount和账户利息类AccountInterest
 class BankAccount {  
        private int accountAge;  
        private int creditScore;  
        private AccountInterest accountInterest;  
          
        public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest) {  
            this.accountAge = accountAge;  
            this.creditScore = creditScore;  
            this.accountInterest = accountInterest;  
        }  
          
        public int getAccountAge() {  
            return this.accountAge;  
        }  
          
        public int getCreditScore() {  
            return this.creditScore;  
        }  
          
        public AccountInterest getAccountInterest() {  
            return this.accountInterest;  
        }  
    
        public double calculateInterestRate() {  
            if (this.creditScore > 800) {  
                return 0.02;  
            }  
              
            if (this.accountAge > 10) {  
                return 0.03;  
            }  
              
            return 0.05;  
        }  
    }  

  class AccountInterest {  
        private BankAccount account;  
          
        public AccountInterest(BankAccount account) {  
            this.account = account;  
        }  
          
        public BankAccount getAccount() {  
            return this.account;  
        }  
          
        public double getInterestRate() {  
            return account.calculateInterestRate();  
        }  
          
        public boolean isIntroductoryRate() {  
            return (account.calculateInterestRate() < 0.05);  
        }  
    }  
    说明:很明显AccountInterest使用calculateInterestRate()方法更为频繁,它更希望得到该方法
    ----------------------------------------------------------------------------

    重构(搬移函数)
    将calculateInterestRate()方法从BankAccount类搬移到AccountInterest类中
      
    class BankAccount {  
        private int
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值