1. 程式人生 > 其它 >spring中BeanPostProcessor 實現策略模式

spring中BeanPostProcessor 實現策略模式

技術標籤:java

視訊解碼列舉

public enum VideoType {

    WMV("wmv"),
    AVI("avi");

    private String desc;

    VideoType(String desc) {
        this.desc = desc;
    }

    public String getDesc() {
        return desc;
    }
}

解碼介面

public interface IDecoder {

    VideoType type(
); String decode(String data); }

WMV解碼功能

@Service
public class WMVDecoder implements IDecoder {
    @Override
    public VideoType type() {
        return VideoType.WMV;
    }

    @Override
    public String decode(String data) {
        return this.type().getDesc() + ": " + data;
    }
}

AVI解碼功能

@Service
@Slf4j
public class AVIDecoder implements IDecoder, InitializingBean {
    @Override
    public VideoType type() {
        return VideoType.AVI;
    }

    @Override
    public String decode(String data) {
        return this.type().getDesc() + " : " + data;
    }

    @Override
public void afterPropertiesSet() throws Exception { log.info("init AVIDecoder afterPropertiesSet"); } }

解碼Manager

實現 BeanPostProcessor介面,並快取 VideoType 與 IDecoder對應關係

@Service
@Slf4j
public class DecodeManager implements BeanPostProcessor {

    private static final Map<VideoType, IDecoder> viderTypeInedx =
            new HashMap<>(VideoType.values().length);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if (!(bean instanceof IDecoder)) {
            return bean;
        }
        IDecoder decoder = (IDecoder) bean;
        VideoType type = decoder.type();
        if (viderTypeInedx.containsKey(type)) {
            throw new IllegalStateException("重複註冊");
        }
        log.info("Load Decode {} for video type{} ", decoder.getClass(), type.getDesc());
        viderTypeInedx.put(type, decoder);
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof IDecoder)) {
            return bean;
        }
        log.info("BeanPostProcessor after init :{}", bean.getClass());
        return null;
    }

    public String decode(VideoType type, String data) {
        String result = null;
        switch (type) {
            case AVI:
                result = viderTypeInedx.get(VideoType.AVI).decode(data);
                break;
            case WMV:
                result = viderTypeInedx.get(VideoType.WMV).decode(data);
                break;
            default:
                log.info("error");
        }
        return result;
    }
}

測試用例:

  @Autowired
    private DecodeManager decodeManager;

    @Test
    public void testDecode() {
        //獲取隨機解碼器
        VideoType videoType = VideoType.values()[new Random().nextInt(VideoType.values().length)];

        decodeManager.decode(videoType, "解碼資料~");
    }