1700456011
1700456012
public static void main(String[]args){
1700456013
1700456014
InstallSoftware invoker=new InstallSoftware();
1700456015
1700456016
invoker.installWizard(new Wizard());
1700456017
1700456018
}
1700456019
1700456020
}
1700456021
1700456022
以上程序很简单,运行结果和随机数有关,每次的执行结果都不相同,需要读者自己运行并查看结果。程序虽然简单,但是隐藏的问题可不简单,思考一下程序有什么问题。Wizard类把太多的方法暴露给InstallSoftware类,两者的朋友关系太亲密了,耦合关系变得异常牢固。如果要将Wizard类中的first方法返回值的类型由int改为boolean,就需要修改InstallSoftware类,从而把修改变更的风险扩散开了。因此,这样的耦合是极度不合适的,我们需要对设计进行重构,重构后的类图如图5-4所示。
1700456023
1700456024
1700456025
1700456026
1700456027
图5-4 重构后的软件安装过程类图
1700456028
1700456029
在Wizard类中增加一个installWizard方法,对安装过程进行封装,同时把原有的三个public方法修改为private方法,如代码清单5-11所示。
1700456030
1700456031
代码清单5-11 修改后的导向类实现过程
1700456032
1700456033
public class Wizard{
1700456034
1700456035
private Random rand=new Random(System.currentTimeMillis());
1700456036
1700456037
//第一步
1700456038
1700456039
private int first(){
1700456040
1700456041
System.out.println(“执行第一个方法……”);
1700456042
1700456043
return rand.nextInt(100);
1700456044
1700456045
}
1700456046
1700456047
//第二步
1700456048
1700456049
private int second(){
1700456050
1700456051
System.out.println(“执行第二个方法……”);
1700456052
1700456053
return rand.nextInt(100);
1700456054
1700456055
}
1700456056
1700456057
//第三个方法
1700456058
1700456059
private int third(){
1700456060
[
上一页 ]
[ :1.700456011e+09 ]
[
下一页 ]