设计模式之工厂模式和策略模式

来源:互联网 发布:乐视视频下载mac 编辑:程序博客网 时间:2024/06/10 20:05

工厂模式的使用场景是为了统一管理对象的实例化,当对象改变的时候不需要改动太大代码量就能增加或修改,以便代码的维护。


首先有一个Car的接口

public interface Car{  public void run();}


接下来宝马和奔驰分别实现了该接口


</pre>public class BMW implements Car{<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public void run() {<span style="white-space:pre"></span>System.out.println("宝马在飞驰");<span style="white-space:pre"></span>}}<pre name="code" class="java">

</pre>public class Benz implements Car{<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public void run() {<span style="white-space:pre"></span>System.out.println("奔驰在飞驰");<span style="white-space:pre"></span>}}<pre name="code" class="java">


汽车工厂:


public class CarFactory {

public Car createCar(String car){
if("BMW".equals(car)){
return new BMW();
}else{
return new Benz();
}
}

}


简单工厂模式就是在工厂里面生产用户需要的对象,不需要用户实例化,对象由工厂维护。


贴一下在写的代码里的应用:

import java.util.List;


import com.toone.xmdj.util.validator.ValidatorResultMessge;


public class ValidatorTypeContext {

private ValidatorTypeAbstract val = null;

public ValidatorTypeContext(String str,Object obj){
if("Map".equals(str)){
ValidatorTypeWithMapUtil cs = new ValidatorTypeWithMapUtil(obj);
val=cs;
   }else if("Entity".equals(str)){
    ValidatorTypeWithEntityUtil cs = new ValidatorTypeWithEntityUtil(obj);
    val=cs;
    System.out.println();
   }
}

public ValidatorResultMessge selectValidatorTypeMap(Object obj,List<String> checkList) throws Exception{
ValidatorResultMessge result = new ValidatorResultMessge();
if("checkNotNull".equals(obj)){
    result = val.checkNotNull(checkList);
   }else if("checkIsNumber".equals(obj)){
    result = val.checkIsNumber(checkList);
   }else if("checkIsMobile".equals(obj)){
    result = val.checkIsMobile(checkList);
   }
return result;
}


}


我的代码里是通过Context构造方法实例化ValidatorTypeAbstract 对象,并在selectValidatorTypeMap使用这个实例化的对象。同时我这里也采用了策略模式,ValidatorTypeAbstract 作为抽象的策略类,ValidatorTypeWithMapUtil 和ValidatorTypeWithEntityUtil 分别是实现策略类的具体策略。通过Context(环境类)对策略类进行实例化,并使用相应的方法。

0 0
原创粉丝点击