Menu
Coddy logo textTech

도형 컬렉션

Coddy Lua 여정의 객체 지향 프로그래밍 (Object Oriented Programming) 섹션에 포함된 레슨. 70개 중 59번째.

challenge icon

챌린지

쉬움

이제 모든 기능을 갖춘 Rectangle 및 Circle 클래스가 있으므로, 여러 shape를 함께 관리할 수 있는 ShapeCollection 클래스를 만들어 보겠습니다. 이는 composition의 훌륭한 예입니다. collection은 shape가 "has"하는 것이지 shape가 "being"하는 것이 아닙니다.

확장 중인 프로젝트에 새 파일을 추가합니다.

  • Shape.lua: 기본 Shape 클래스입니다(변경되지 않음).
  • Rectangle.lua: :getArea():getPerimeter()를 포함하는 Rectangle 클래스입니다.
  • Circle.lua: :getArea():getPerimeter()를 포함하는 Circle 클래스입니다.
  • ShapeCollection.lua: 내부에 shapes를 stored하는 새 클래스를 Create합니다. empty shapes list를 초기화하는 :new() constructor, collection에 any shape를 add하는 :addShape(shape) method, currently stored된 shapes가 how many인지 반환하는 :count() method를 포함합니다.
  • main.lua: 모듈을 require하여 모든 것을 결합합니다. input에서 dimensions를 read하고, Rectangle과 Circle을 create한 다음, 둘 다 ShapeCollection에 add하고, collection의 count에 이어 각 shape의 이름을 Print합니다(added된 order대로).

ShapeCollection은 rectangles 또는 circles 중 무엇을 stored하는지 알 필요가 없습니다. 단지 shapes를 보유할 뿐입니다. 이는 polymorphism을 통해 common interface로 서로 다른 object types를 일관되게 다룰 수 있음을 보여 줍니다.

Input: 세 줄: width (number), height (number), radius (number)입니다.

Output: 세 줄: collection에 있는 shapes의 count, 그다음 added된 first shape의 이름, 그다음 added된 second shape의 이름입니다.

직접 해보기

-- Rectangle 모듈을 불러옵니다
local Rectangle = require('Rectangle')

-- Circle 모듈을 불러옵니다
local Circle = require('Circle')

-- ShapeCollection 모듈을 불러옵니다
local ShapeCollection = require('ShapeCollection')

-- 입력에서 너비와 높이를 읽습니다
local width = tonumber(io.read())
local height = tonumber(io.read())
local radius = tonumber(io.read())

-- 주어진 크기로 새 Rectangle 인스턴스를 생성합니다
local rect = Rectangle:new(width, height)

-- 주어진 반지름으로 새 Circle 인스턴스를 생성합니다
local circ = Circle:new(radius)

-- 새 ShapeCollection을 생성합니다
local collection = ShapeCollection:new()

-- 두 도형을 컬렉션에 추가합니다
collection:addShape(rect)
collection:addShape(circ)

-- 컬렉션에 있는 도형의 개수를 출력합니다
print(collection:count())

-- 추가된 순서대로 각 도형의 이름을 출력합니다
for i = 1, collection:count() do
    print(collection.shapes[i]:getName())
end

객체 지향 프로그래밍 (Object Oriented Programming)의 모든 레슨

직접 연습해 보세요: 온라인 Lua 컴파일러