이것으로 끝입니다(R6 객체의 종료)
R6 클래스가 객체가 생성될 때 사용자 정의 코드를 실행하는 public initialize() 메서드를 정의할 수 있듯이, 객체가 파괴될 때 사용자 정의 코드를 실행하는 public finalize() 메서드도 정의할 수 있어요. finalize()는 인수를 받지 않아야 합니다. 보통 데이터베이스나 파일 연결을 닫거나, 전역 options() (docs)나 그래픽 par() (docs) 파라미터처럼 부작용을 되돌리는 데 사용해요.
코드 템플릿은 다음과 같아요.
thing_factory <- R6Class(
"Thing",
public = list(
initialize = function(x, y, z) {
# do something
},
finalize = function() {
# undo something
}
)
)
finalize() 메서드는 R의 자동 가비지 컬렉터가 객체를 메모리에서 제거할 때 호출됩니다. gc() (docs)를 입력해 가비지 컬렉션을 강제로 실행할 수 있어요.
이 연습은 강의의 일부입니다
R에서 S3와 R6로 배우는 Object-Oriented Programming
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Microwave_factory is predefined
microwave_oven_factory
# Complete the class definition
smart_microwave_oven_factory <- R6Class(
"SmartMicrowaveOven",
inherit = ___, # Specify inheritance
private = list(
# Add a field to store connection
___ = ___
),
public = list(
initialize = function() {
# Connect to the database
___$___ = ___(___(), "___")
},
get_cooking_time = function(food) {
dbGetQuery(
private$conn,
sprintf("SELECT time_seconds FROM cooking_times WHERE food = '%s'", food)
)
},
finalize = function() {
# Print a message
___("___")
# Disconnect from the database
___(___$___)
}
)
)
# Create a smart microwave object
a_smart_microwave <- ___
# Call the get_cooking_time() method
___