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

工厂设计模式与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的属性完成空中,从而使得整体代码简洁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值