策略者模式
可减少代码中的if else 判断,通过类型匹配需求
例如需求:需求定义多种上传文件模式,根据类型进行匹配上传接口
1.首先定义一个抽象接口
/**
* 上传文件
*/
public abstract class Channel {
public abstract void channelData(String file);
}
2.实现抽象方法,两种上传方式
/**
* fast dfs 上传文件
*/
public class FastDfsChannel extends Channel {
@Override
public void channelData(String file) {
System.out.println("FastDfsChannel 通道上传:" + file + "已上传到 fastdfs服务器");
}
}
/**
* oss 上传文件
*/
public class OssChannel extends Channel {
@Override
public void channelData(String file) {
System.out.println("OssChannel 通道上传:" + file + "已上传到 oss服务器");
}
}
3.通过枚举进行类型匹配
public enum ChannelEnum {
fastdfsChannel("fastdfs", new FastDfsChannel()),
ossChannel("oss", new OssChannel()),
;
private String type;
private Channel channel;
ChannelEnum(String type, Channel channel) {
this.type = type;
this.channel = channel;
}
//匹配
public static Channel match(String type) {
ChannelEnum[] values = ChannelEnum.values();
for (ChannelEnum value : values) {
if (value.type.equals(type)) {
return value.channel;
}
}
return null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
}
4.测试结果
@Test
public void storageTest2() {
//通过类型进行匹配上传通道
Channel channel = ChannelEnum.match("oss");
channel.channelData("策略模式.txt");
}