反射实现动态工厂设计模式
程序员文章站
2022-03-09 21:52:38
...
package com.zokkk.spring;
interface IMessage{
void send();
}
interface CloudMessage{
void send();
}
class MyIMessage implements IMessage{
public void send() {
System.out.println("IMessage:MyIMessage");
}
}
class MyCloudMessage implements CloudMessage{
public void send() {
System.out.println("CloudMessage:MyCloudeMessage");
}
}
class Factory{
public static<T> T getInstance(String className,Class<T> clazz) {
T instance=null;
try {
instance=(T)Class.forName(className).getDeclaredConstructor().newInstance();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return instance;
}
}
public class JavaDemo {
public static void main(String[] args) {
IMessage iMessage=Factory.getInstance("com.zokkk.spring.MyIMessage", IMessage.class);
CloudMessage cMessage=Factory.getInstance("com.zokkk.spring.MyCloudMessage", CloudMessage.class);
iMessage.send();
cMessage.send();
}
}
运行结果:
上一篇: 钉钉消息怎么设置成振动
下一篇: 反射机制和工厂设计模式学习笔记