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

反射实现动态工厂设计模式

程序员文章站 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();
	}
}

运行结果:

反射实现动态工厂设计模式

相关标签: Java