On this page
设计模式
策略模式
Java实现
Tag.class
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Tag{
String code();
String name() default "";
}TagImpl.class
public class TagImpl implements Tag{
private final String code;
private final String name;
public TagImpl(String code, String name) {
this.code = code;
this.name = name;
}
public TagImpl(String code) {
this.code = code;
this.name = "";
}
@Override
public String code() {
return code;
}
@Override
public String name() {
return name;
}
@Override
public Class<? extends Annotation> annotationType() {
return Tag.class;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
boolean son = o instanceof Tag;
if (!son) {
return false;
}
Tag that = (Tag) o;
return Objects.equals(code, that.code()) ;
}
@Override
public int hashCode() {
return (127 * "code".hashCode()) ^ code.hashCode();
}
}统一接口Api.class
public interface Api{
void execute();
}
@Tag(code = "Def")
public class DefaultApi implements Api{
public void execute(){
}
}统一管理Api的实现类
public class ApiManager{
private static final Map<Tag,Api> apiStore = new HashMap<>();
public static void addApi(Api api){
Tag tag = api.getClass().getAnnotation(Tag.class);
apiStore.put(tag,api);
}
public static Api getApi(String code){
TagImpl tag = new TagImpl(code);
apiStore.get(tag);
}
}