정보 은닉
Coddy GDScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 65개 중 28번째.
정보 은닉은 private 변수보다 한 단계 더 나아갑니다. 클래스를 사용하는 코드는 클래스의 public 메서드가 어떤 작업을 하는지에만 의존하고, 클래스가 데이터를 어떻게 저장하는지에는 전혀 의존하지 않습니다. 그러면 해당 코드를 건드리지 않고도 저장 방식을 바꿀 수 있습니다.
# inventory.gd
class_name Inventory
extends RefCounted
var _counts: Dictionary = {}
func add(item: String, amount: int) -> void:
_counts[item] = _counts.get(item, 0) + amount
func count(item: String) -> int:
return _counts.get(item, 0)
func remove(item: String, amount: int) -> bool:
if count(item) < amount:
return false
_counts[item] -= amount
return truemain.gd는 add(), count(), remove()를 호출하며 Dictionary를 직접 다루지 않습니다. 나중에 Inventory가 대신 슬롯의 Array를 저장하더라도 inventory.gd만 변경하면 됩니다.
Array 또는 Dictionary를 반환하는 getter는 주의해서 사용하세요. GDScript는 이러한 값을 참조로 전달합니다. 호출자는 복사본이 아니라 객체 자체의 Array를 받아 클래스의 메서드를 거치지 않고도 변경할 수 있습니다:
# quest_log.gd
var _quests: Array[String] = ["Find the key"]
func get_quests() -> Array[String]:
return _quests# main.gd
var journal := QuestLog.new()
var quests := journal.get_quests()
quests.append("Skip the boss")
print(journal.get_quests()) # ["Find the key", "Skip the boss"]대신 복사본을 반환하세요. duplicate()는 같은 요소를 가진 새 Array를 만들므로, 복사본을 변경해도 객체에는 영향을 주지 않습니다:
func get_quests() -> Array[String]:
return _quests.duplicate()Dictionary 또는 다른 Array를 담고 있는 Array에는 duplicate(true)를 사용하세요. 내부 Array와 Dictionary도 복사합니다.
챌린지
쉬움playlist.gd 파일에 Playlist 클래스를 작성하세요. 이 클래스는 노래 제목을 비공개 배열 _songs에 보관하며, 다른 코드는 다음 메서드만 사용합니다.
add(title)는 제목을 추가하고true를 반환합니다. 제목이 이미 재생 목록에 있으면 아무것도 변경하지 않고false를 반환합니다.remove(title)는 제목을 제거하고true를 반환하며, 제목이 없으면false를 반환합니다.count()는 노래 수를 반환합니다.get_titles()는 추가된 순서대로 제목의 복사본을 반환합니다.
제공된 코드는 명령의 개수를 읽은 다음, 한 줄에 하나씩 명령(add Blue Sky 또는 remove Blue Sky)을 읽고 결과를 출력합니다. 마지막에는 get_titles()에서 배열을 가져와 Intruder를 추가하고 순서를 뒤집은 다음, 노래 수와 제목을 출력합니다. 이러한 변경 사항이 재생 목록에 영향을 주어서는 안 됩니다. 다음 명령 add Blue Sky, add Rain, add Blue Sky에 대해 출력되는 내용은 다음과 같습니다.
Added: Blue Sky
Added: Rain
Already in the playlist: Blue Sky
Songs: 2
Blue Sky, Rain코드는 playlist.gd에 작성하세요. main.gd에는 제공된 입출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
extends Node
func _ready():
# 제공된 입출력 코드: 그대로 유지하세요
var playlist := Playlist.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ", true, 1)
var title := parts[1]
if parts[0] == "add":
if playlist.add(title):
print("Added: " + title)
else:
print("Already in the playlist: " + title)
elif playlist.remove(title):
print("Removed: " + title)
else:
print("Not found: " + title)
# 반환받은 목록을 변경하려는 코드
var titles := playlist.get_titles()
titles.append("Intruder")
titles.reverse()
print("Songs: %d" % playlist.count())
print(", ".join(playlist.get_titles()))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러