FactoryBox 一個(gè)Android 代碼生成列子
使用google的auto-service和AbstractProcessor進(jìn)行代碼生成??戳瞬簧僦v解AbstractProcessor的教程,后來我一直在需要找其應(yīng)用的實(shí)例。后來在項(xiàng)目中的一個(gè)配置文件經(jīng)常改動(dòng)想到了自動(dòng)生成代碼,于是考慮實(shí)踐一下
例子
1、需要實(shí)現(xiàn)的接口
public interface Event {
void onEvent();
}
2、具體的實(shí)現(xiàn)接口的類
@FactoryBox(key = "destroy", product = Event.class)
public class DestroyEvent implements Event {
@Override
public void onEvent() {
}
}
@FactoryBox(key = "resume", product = Event.class)
public class ResumeEvent implements Event {
@Override
public void onEvent() {
}
}
3、自動(dòng)生成部分
package com.owant.createcode.testcode;
import java.lang.Exception;
import java.lang.String;
public final class EventFactory {
public static Event create(String key) throws Exception {
if("sub_event".equals(key)) {
return new com.owant.createcode.sub.SubEvent();
} else if("create".equals(key)) {
return new com.owant.createcode.CreateEvent();
} else if("destroy".equals(key)) {
return new com.owant.createcode.testcode.DestroyEvent();
} else if("resume".equals(key)) {
return new com.owant.createcode.testcode.ResumeEvent();
} else {
throw new Exception(String.format("沒有到key=%s對(duì)應(yīng)的實(shí)現(xiàn)",key));
}
}
}
好處
實(shí)現(xiàn)工廠模式的拓展,不關(guān)心工廠的實(shí)現(xiàn),工廠由代碼進(jìn)行生成。減少了更改。
https://github.com/owant/FactoryBox