
public class Teacher
{
//老师对班长发布命令,清点女生
public void commond(GroupLeader groupLeader)
{
List<Girl> listGirls = new ArrayList();
//初始化女生
for (int i = 0; i < 20; i++)
{
listGirls.Add(new Girl());
//告诉班长开始执行清点任务
groupLeader.countGirls(listGirls);
}
}
}班长类:public class GroupLeader
{
//清点女生数量
public void countGirls(List<Girl> listGirls)
{
//输出女生数量:listGirls.size()
}
}女生类:public class Girl
{
}场景类:public class Client
{
public static void main(String[] args)
{
Teacher teacher = new Teacher();
//老师发布命令
teacher.commond(new GroupLeader());
}
}
public class Teacher
{
//老师对班长发布命令,清点女生
public void commond(GroupLeader groupLeader)
{
//告诉班长开始执行清点任务
groupLeader.countGirls();
}
}修改后的班长类:public class GroupLeader
{
private List<Girl> listGirls;
public GroupLeader(List<Girl> _listGirls)
{
this.listGirls = _listGirls;
}
//清点女生数量
public void countGirls(List<Girl> listGirls)
{
//输出女生数量:this.listGirls.size()
}
}修改后的场景类:public class Client
{
public static void main(String[] args)
{
//产生一个女生群体
List<Girl> listGirls = new ArrayList<Girl>();
//初始化女生
for (int i = 0; i < 20; i++)
{
listGirls.Add(new Girl());
}
Teacher teacher = new Teacher();
//老师发布命令
teacher.commond(new GroupLeader(listGirls));
}
}
public class Wizard
{
private Random rand = new Random(System.currentTimeMillis());
public int first()
{
//执行第一个方法
return rand.nextInt(100);
}
public int second()
{
//执行第二个方法
return rand.nextInt(100);
}
public int third()
{
//执行第三个方法
return rand.nextInt(100);
}
}public class InstallSoftware
{
public void installWizard(Wizard wizard)
{
int first = wizard.first();
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()
{
//执行第一个方法
return rand.nextInt(100);
}
private int second()
{
//执行第二个方法
return rand.nextInt(100);
}
private int third()
{
//执行第三个方法
return rand.nextInt(100);
}
//软件安装过程
public void installWizard()
{
int first = wizard.first();
if (first > 50)
{
int second = wizard.second();
if (second > 50)
{
int third = wizard.third();
if (third > 50)
wizard.first();
}
}
}
} 这样Wizard类就只对外公布了一个public方法,即便修改first方法的返回值,影响的也仅仅只是Wizard本身,其他类不受影响,这就显示了类的高内聚性。public class InstallSoftware
{
public void installWizard(Wizard wizard)
{
//直接调用
wizard.installWizard();
}
}注意:迪米特法则要求类“羞涩”一点,尽量不要对外公布太多public犯法和非静态的public变量,尽量内敛,多使用private,package-private、protected等访问权限。设计模式学习之——六大设计原则之五:迪米特法则,布布扣,bubuko.com
原文:http://blog.csdn.net/fu222cs98/article/details/21426339