打字猴:1.700457516e+09
1700457516 设计模式之禅 [:1700453942]
1700457517 设计模式之禅 8.4 工厂方法模式的扩展
1700457518
1700457519 工厂方法模式有很多扩展,而且与其他模式结合使用威力更大,下面将介绍4种扩展。
1700457520
1700457521 1.缩小为简单工厂模式
1700457522
1700457523 我们这样考虑一个问题:一个模块仅需要一个工厂类,没有必要把它产生出来,使用静态的方法就可以了,根据这一要求,我们把上例中的AbstarctHumanFactory修改一下,类图如图8-3所示。
1700457524
1700457525
1700457526
1700457527
1700457528 图8-3 简单工厂模式类图
1700457529
1700457530 我们在类图中去掉了AbstractHumanFactory抽象类,同时把createHuman方法设置为静态类型,简化了类的创建过程,变更的源码仅仅是HumanFactory和NvWa类,HumanFactory如代码清单8-13所示。
1700457531
1700457532 代码清单8-13 简单工厂模式中的工厂类
1700457533
1700457534 public class HumanFactory{
1700457535
1700457536 public static<T extends Human>T createHuman(Class<T>c){
1700457537
1700457538 //定义一个生产出的人种
1700457539
1700457540 Human human=null;
1700457541
1700457542 try{
1700457543
1700457544 //产生一个人种
1700457545
1700457546 human=(Human)Class.forName(c.getName()).newInstance();
1700457547
1700457548 }catch(Exception e){
1700457549
1700457550 System.out.println(“人种生成错误!”);
1700457551
1700457552 }
1700457553
1700457554 return(T)human;
1700457555
1700457556 }
1700457557
1700457558 }
1700457559
1700457560 HumanFactory类仅有两个地方发生变化:去掉继承抽象类,并在createHuman前增加static关键字;工厂类发生变化,也同时引起了调用者NvWa的变化,如代码清单8-14示。
1700457561
1700457562 代码清单8-14 简单工厂模式中的场景类
1700457563
1700457564 public class NvWa{
1700457565
[ 上一页 ]  [ :1.700457516e+09 ]  [ 下一页 ]