溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何整合工廠設計模式來應用Annotation操作

發(fā)布時間:2021-10-13 11:26:23 來源:億速云 閱讀:123 作者:iii 欄目:編程語言

本篇內容介紹了“如何整合工廠設計模式來應用Annotation操作”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

現(xiàn)在已經(jīng)清楚了Annotation的整體作用,但是Annotation到底在開發(fā)中能做哪些事情呢?為了進一步理解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 JavaAPIDemo {public static void main(String[] args) throws Exception {//IMessage msg = Factory.getInstance(MessageImpl.class);//msg.send("www.mldn.cn")MessageService messageService=new MessageService();
        messageService.send("www.mldn.cn");
    }
}@Retention(RetentionPolicy.RUNTIME)@interface UserMessage{public Class <?> clazz();
}@UserMessage(clazz =MessageImpl.class )  //利用Annotation實現(xiàn)了類的使用class MessageService{private IMessage message;public MessageService(){
        UserMessage use=MessageService.class.getAnnotation(UserMessage.class);this.message = (IMessage)Factory.getInstance(use.clazz());  //直接通過Annotation獲取}public void send(String msg){this.msg.send(msg);
    }
}class Factory  {private Factory() {}public static <T> T getInstance(Class<T> clazz){   //直接返回一個實例化對象try {return (T)new MessageProxy().bind(clazz.getDeclaredConstructor().newInstance());
        } catch (Exception e) {
            e.printStackTrace();return null;
        }
    }
}interface IMessage {public void send(String msg);
}class MessageImpl implements IMessage {@Overridepublic void send(String msg) {
        System.out.println("【消息發(fā)送】"+msg);
    }
}class NetMessageImpl implements IMessage {@Overridepublic void send(String msg) {
        System.out.println("【網(wǎng)絡消息發(fā)送】"+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("【代理操作】進行消息發(fā)送通道的連接。");return true;
    }public void close() {
        System.out.println("【代理操作】關閉連接通道。");
    }@Overridepublic 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】消息無法進行發(fā)送!");
            }      
        }finally {this.close();
        }
    }
}

執(zhí)行結果:
如何整合工廠設計模式來應用Annotation操作
更換

@UserMessage(clazz =NetMessageImpl.class )

“如何整合工廠設計模式來應用Annotation操作”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注億速云網(wǎng)站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI