http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

Java中可以使用这种设计模式吗?如果是这样,怎么办?如果没有,为什么不呢?

谢谢!

最佳答案

您链接到的同一Wikipedia页面上有Java部分,引用:


因此,未引用对象的“ finalize”方法可能永远不会被调用,或者仅在对象变为未引用之后很久才调用。因此,程序员必须使用dispose pattern之类的资源来手动关闭资源。


void java_example() {
  // open file (acquire resource)
  final LogFile logfile = new LogFile("logfile.txt");

  try {
      logfile.write("hello logfile!");

      // continue using logfile ...
      // throw exceptions or return without worrying about closing the log;
      // it is closed automatically when exiting this block
   } finally {
      // explicitly release the resource
      logfile.close();
   }
}



每次使用资源时,释放资源的负担就由程序员承担。


我认为有一个关于Java 7的提议,它将创建Closeable类,并为try块添加一些语法糖,以使其更加简洁(但您仍然必须编写该try块)。

关于java - Java中可能会出现RAII吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2048743/

10-11 01:30