java设计模式之策略模式(推荐交通工具)

UML图:

/**
 * @description 交通工具
 * 
 * @author shilvfei
 * 
 * @date 2018年5月10日
 */
public interface Vehicle {
	public String travel(double km);
}
package celve.test1.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//这是有效距离区间注解,可以给策略添加有效区间的设置
@Target(ElementType.TYPE) // 表示只能给类添加该注解
@Retention(RetentionPolicy.RUNTIME) // 这个必须要将注解保留在运行时
@interface Km {
	
	int max() default Integer.MAX_VALUE;

	int min() default Integer.MIN_VALUE;
}
package celve.test1.annotation;

/**
 * @description  步行
 * 
 * @author shilvfei
 * 
 * @date 2018年5月10日
 */
@Km(max=1)
public class Walk implements Vehicle{

	@Override
	public String travel(double km) {
		//走路速度 1m/s
		double time = 0.0;
		if(km!=0.0){
			double m = 1000*km;
			time = m/1;
		}
		return "走路,时间:"+time;
	}

}
package celve.test1.annotation;

/**
 * @description 自行车 
 * 
 * @author shilvfei
 * 
 * @date 2018年5月10日
 */
@Km(min=1,max=3)
public class Bike implements Vehicle{

	@Override
	public String travel(double km) {
		//骑车速度 5m/s
		double time = 0.0;
		if(km!=0.0){
			double m = 1000*km;
			time = m/5;
		}
		return "骑车,时间:"+time;
	}

}
package celve.test1.annotation;

/**
 * @description 自行车 
 * 
 * @author shilvfei
 * 
 * @date 2018年5月10日
 */
@Km(min=1,max=3)
public class Bike implements Vehicle{

	@Override
	public String travel(double km) {
		//骑车速度 5m/s
		double time = 0.0;
		if(km!=0.0){
			double m = 1000*km;
			time = m/5;
		}
		return "骑车,时间:"+time;
	}

}
package celve.test1.annotation;

/**
 * @description
 * 
 * @author shilvfei
 * 
 * @date 2018年5月10日
 */
public class PlayContent {

	private Vehicle vehicle = new Walk();
	private double km;
	
	public  void getUtil(double km){
		this.km = km;
		VehicleFactory factory = new VehicleFactory();
		vehicle = factory.getVehicle(km);
	}
	
	public String goodProject(){
		return vehicle.travel(km);
	}
	
}
package celve.test1.annotation;

import java.io.File;
import java.io.FileFilter;
import java.lang.annotation.Annotation;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description
 * 
 * @author shilvfei
 * 
 * @date 2018年5月10日
 */
public class VehicleFactory {

	//设置扫描包
	private String scanDemoPack = "celve.test1.annotation";
	
	//通过Java的类加载机制(ClassLoader)来动态加载某个class文件到内存当中的
	private ClassLoader classLoader = getClass().getClassLoader();
	
	//策略列表
	private List<Class<? extends Vehicle>> vehicleList;
	
	//根据路的远近 生成相应的策略
	public Vehicle getVehicle(double km){
		 //在策略列表查找策略
		for (Class<? extends Vehicle> classz : vehicleList) {
			Km validKm = handleAnnotation(classz);
			//判断金额是否在注解的区间
			if(validKm.min() < km && km<=validKm.max()){
				try {
					return classz.newInstance();
				} catch (Exception  e) {
					 throw new RuntimeException("策略获得失败");
				} 
			}
		}
		throw new RuntimeException("策略获得失败");
		
		/*if(km<=1){
			return  new Walk();
		}else if(km<=3){
			return  new Bike();
		}else{
			return  new Bus();
		}*/
	}
	
	//处理注解,我们传入一个策略类,返回它的注解
	private Km handleAnnotation(Class<? extends Vehicle> classz){
		Annotation[] annotations = classz.getAnnotations();
		if (annotations == null || annotations.length == 0) {
            return null;
        }
		for (int i = 0; i < annotations.length; i++) {
			if(annotations[i] instanceof Km){
				return (Km) annotations[i];
			}
		}
		return null;
	}
	
	//单例 执行init()方法
	public VehicleFactory() {
		init();
	}
	
	//在工厂初始化时要初始化策略列表
	private void init(){
		vehicleList = new ArrayList<>();
		File[] resource = getResource();//获取所有的class文件
		Class<Vehicle> classz = null;
		try {
			classz = (Class<Vehicle>) classLoader.loadClass(Vehicle.class.getName());
		} catch (ClassNotFoundException e) {
			 throw new RuntimeException("未找到策略接口");
		}
		for (int i = 0; i < resource.length; i++) {
			 //载入包下的类
			try {
				Class<?> loadClass = classLoader.loadClass(scanDemoPack+"."+resource[i].getName().replace(".class", ""));//celve.test1.annotation.Bike 
				 //判断是否是Vehicle的实现类并且不是Vehicle它本身,满足的话加入到策略列表
				if(Vehicle.class.isAssignableFrom(loadClass) && loadClass != classz){
					vehicleList.add((Class<? extends Vehicle>) loadClass);
				}
				
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	//获取扫描的包下面所有的class文件
	public File[] getResource(){
		try {
			File file = new File(classLoader.getResource(scanDemoPack.replace('.', '/')).toURI());
			File[] listFiles = file.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					if(pathname.getName().endsWith(".class")){//我们只扫描class文件
						return true;
					}
					return false;
				}
			});
			return listFiles;
		} catch (URISyntaxException e) {
			throw new RuntimeException("未找到策略资源");
		}
	}
	
}

猜你喜欢

转载自my.oschina.net/u/3568600/blog/1810063
今日推荐