//Printer接口
interface IPrinter {
//接口printByString方法声明
public void printByString(String str);
}
//MyPrinter实现Printer接口
class MyPrinter implements IPrinter {
public void printByString(String str) {
System.out.println(str);
}
}
//IPrinter对象工厂,用于创建实现接口的类对象
class PrinterFactory {
String str = "MyPrinter";//通过字符串寻找实现接口的类,字符串可从文件中读取获得,从而实现IOC模式
//工厂方法,返回IPrinter接口实例
public static IPrinter createPrinter() throws InstantiationException,
ClassNotFoundException, IllegalAccessException {
return (IPrinter) Class.forName(str).newInstance();//返回IF_Printer接口实例
}
}
测试方法
public static void main(String[] args) {
try {
PrinterFactory.createPrinter().printByString("Hello World~!");
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
factory(工厂) 模式简单示例
最新推荐文章于 2022-10-03 10:29:56 发布
本文介绍了一种基于Java的IOC(Inversion of Control)模式的应用案例。通过定义Printer接口及其实现类MyPrinter,利用工厂模式创建接口实例,展示了如何通过字符串动态指定具体实现类,实现了对象创建过程的解耦。
782

被折叠的 条评论
为什么被折叠?



