资源获取即初始化模式
public class ResourceAcquisitionsInitialization {
/**
* Resource Acquisition Is Initialization pattern【资源获取即初始化】:
* 用于实现异常安全的资源管理,资源分配在对象创建时完成,资源释放在对象销毁时完成。
*/
@Test
public void all() throws Exception {
try (SlidingDoor door = new SlidingDoor();) {
door.welcome();
}
}
}
@Slf4j
class SlidingDoor implements AutoCloseable {
public SlidingDoor() {
log.info("door is open");
}
public void welcome() {
log.info("Walking in.");
}
@Override
public void close() throws Exception {
log.info("door is auto close");
}
}