//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());
}
}
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());
}
}
本文介绍了一个使用Java实现的简单IOC(控制反转)模式示例。通过定义Printer接口及其实现类MyPrinter,并利用工厂模式创建接口实例,展示了如何通过字符串配置来决定创建哪个实现了指定接口的类。
774

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



