Shapeコレクション
CoddyのLuaジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 59/70。
チャレンジ
簡単Rectangle クラスと Circle クラスの完全な機能がそろったので、複数の shape をまとめて管理できる ShapeCollection クラスを作成しましょう。これは合成のよい例です。この collection は shape を「持つ」のであって、shape「そのもの」ではありません。
成長中のプロジェクトに新しいファイルを追加します。
Shape.lua:基本の Shape クラス(変更なし)。Rectangle.lua::getArea()と:getPerimeter()を備えた Rectangle クラス。Circle.lua::getArea()と:getPerimeter()を備えた Circle クラス。ShapeCollection.lua:shape を内部に格納する新しいクラスを作成します。空の shape の list を初期化する:new()constructor、collection に any shape を追加する:addShape(shape)method、currently stored されている shape の数を返す:count()method を含めます。main.lua:module を require してすべてをまとめます。input から dimensions を read し、Rectangle と Circle を作成し、both を ShapeCollection に add してから、collection の count、続いて各 shape の名前を(they were add された order で)print します。
ShapeCollection は、rectangles と circles のどちらを stored しているかを知る必要はありません。shape を保持するだけです。これは、polymorphism によって、共通の interface を通じて異なる object type を均一に扱えることを示しています。
Input: Three lines:width(number)、height(number)、radius(number)。
Output: Three lines:collection 内の shape の count、次に first shape の name、最後に second shape の name。
自分で試してみよう
-- 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
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Luaオンラインコンパイラ