源代码如下://原始代码
public class Wizard { private Random rand = new Random(System.currentTimeMillis()); //第一步 public int first(){ System.out.println("执行第一个方法..."); return rand.nextInt(100); } //第二步 public int second(){ System.out.println("执行第二个方法..."); return rand.nextInt(100); } //第三个方法 public int third(){ System.out.println("执行第三个方法..."); return rand.nextInt(100); } } public class InstallSoftware { public void installWizard(Wizard wizard){ int first = wizard.first(); //根据first返回的结果,看是否需要执行second if(first>50){ int second = wizard.second(); if(second>50){ int third = wizard.third(); if(third >50){ wizard.first(); } } } } } public class Client { public static void main(String[] args) { InstallSoftware invoker = new InstallSoftware(); invoker.installWizard(new Wizard()); } }
//源代码如下:
public class Wizard { private Random rand = new Random(System.currentTimeMillis()); //第一步 private int first(){ System.out.println("执行第一个方法..."); return rand.nextInt(100); } //第二步 private int second(){ System.out.println("执行第二个方法..."); return rand.nextInt(100); } //第三个方法 private int third(){ System.out.println("执行第三个方法..."); return rand.nextInt(100); } //软件安装过程 public void installWizard(){ int first = this.first(); //根据first返回的结果,看是否需要执行second if(first>50){ int second = this.second(); if(second>50){ int third = this.third(); if(third >50){ this.first(); } } } } } public class InstallSoftware { public void installWizard(Wizard wizard){ //不废话,直接调用 wizard.installWizard(); } } public class Client { public static void main(String[] args) { InstallSoftware invoker = new InstallSoftware(); invoker.installWizard(new Wizard()); } }
//Someone类有一个方法接受一个Friend类型的变量:
public class Someone{
public void operation1( Friend friend ){
Stranger stranger = friend.provide();
stranger.operation3() ;
}
}
//所以Someone和Friend是朋友类(直接通讯的类)。同理,Friend类持有一个Stranger类的私有对象,他们是朋友类:
public class Friend{
private Stranger stranger = new Stranger();
public void operation2(){ }
public Stranger provide(){
return stranger;
}
}
现在仔细观察上述结构,会发现狭义迪米特法则一个明显的缺点:会在系统里造出大量的小方法,散落在系统的各个角落。这些方法仅仅是传递间接的调用,因此与系统的商务逻辑无关,当设计师试图从一张类图看出总体的框架时,这些小的方法会造成迷惑和困扰。遵循迪米特法则会使一个系统的局部设计简化,因为每一个局部都不会和远距离的对象有直接关联。但是,这也会造成系统的不同模块之间的通信效率降低,也会使系统的不同模块之间不容易协调。
publicabstractclassAbstractStranger{
abstractvoidoperation3();
}
publicclassStrangerextendsAbstractStranger{
publicvoidoperation3(){}
}
publicclassSomeone{
publicvoidoperation1(Friendfriend){
AbstractStrangerstranger=friend.provide();
stranger.operation3();
}
}
publicclassFriend{
privateStrangerstranger=newStranger();
publicvoidoperation2(){}
publicAbstractStrangerprovide(){
returnstranger;
}
}

以上就是关于迪米特法则的全部内容,相信你一定会非常满意。
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-138-2.html
为了他的电商事业
等着你们的舞台回归秀