欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(反射与Annotation)工厂设计模式与Annotation整合

程序员文章站 2022-03-09 20:33:14
...

工厂设计模式与Annotation整合

到底Annotation在开发之中能做哪些事情?

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class AnnotationDemo{
    public static void main(String[] args) throws Exception {

        MessageService messageService = new MessageService();
        messageService.send("hellow word!");

    }
}
//创建一个Annotation在运行时使用
@Retention(RetentionPolicy.RUNTIME)
@interface UseMessage{

    public Class<?> clazz();    //运行时需要设置一个class

}

@UseMessage(clazz = MessageImpl.class)
class MessageService{

    private IMessage1 message;

    public MessageService(){

        UseMessage useMessage = MessageService.class.getAnnotation(UseMessage.class);   //得到一个Annotation对象
        this.message = (IMessage1) Factory.getInsrtance(useMessage.clazz());    //直接通过Annotation获取类

    }

    public void send(String msg){

        this.message.send(msg);

    }

}

interface IMessage1{

    public void send(String msg);

}

class MessageImpl implements IMessage1{

    @Override
    public void send(String msg){
        System.out.println("【消息发送】"+msg);
    }

}


//代理设计
class MessageProxy implements InvocationHandler{

    private Object target;

    public Object bind(Object target){

        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);

    }

    public boolean connect(){

        System.out.println("通道连接...");
        return true;

    }

    public void close(){

        System.out.println("关闭通道...");

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        try{
            if(this.connect()){
                return method.invoke(this.target,args);
            }else{
                throw new Exception("【ERROR】消息无法发送");
            }
        }finally {
            this.close();
        }

    }


}

class Factory{

    private Factory(){}

    public static<T>T getInsrtance(Class<T> clazz){ //直接返回一个实例化的操作对象

        try {
            return (T)new MessageProxy().bind(clazz.getDeclaredConstructor().newInstance());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}

通道连接...
【消息发送】hellow word!
关闭通道...

由于Annotation的存在,所以面向接口的编程处理可以直接利用Anootaion的属性完成空中,从而使得整体代码简洁。