六大设计原则-迪米特原则【Low Of Demeter】

2019-08-26  本文已影响0人  阿甘兄

六大设计原则


迪米特原则

定义:最少知识原则(Least Knowledge Principle,简称 LKP),一
个类对自己需要耦合或者调用的类应该知道的最少。

引出问题:

image.png

类图描述的就是客户端(Client)使用安装器安(InstallSoftware)装压缩包(Wizard)的关系。

public class InstallSoftware {   
        public void installWizard(Wizar wizard){
              int first = wizard.first(); 
              //根据first返回的结果,看是否需要 if(first>50){ 
              int second = wizard.seco if(second>50){ 
              int third = wizard.th if(third >50){ 
              wizard.first(); 
          } 
     }
 } 
/**
 *安装类
 */

public class InstallSoftware { 
    public void installWizard(Wizard wizard){ 
         //不废话,直接调用
         wizard.installWizard(); 
    } 
} 

/**
 *压缩包类
 */
public class Wizard { 
    private Random rand = //第一步
    private int first(){ 
      System.out.printl return rand.nextIn 
    } 
  
//第二步
private int second(){ 
  System.out.printl return rand.nextIn 
} 
  
//第三个方法
private int third(){ 
  System.out.printl return rand.nextIn 
} 
  
//软件安装过程
public void installWiz int first = this.f //根据first返回的结果 if(first>50){ 
  int second = th if(second>50){ 
  int third =  if(third >5 this.fir 
  } 
 } 
}  

原则:
如果一个方法放在本类中,即不增加类间关系,也对本类不产生负面影响,就放置在本类中。

上一篇 下一篇

猜你喜欢

热点阅读