factory(工厂) 模式简单示例

来源:互联网 发布:淘宝pc端链接转换 编辑:程序博客网 时间:2024/06/11 06:42

 
//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());
  }
  }

原创粉丝点击