0
0

More than 1 year has passed since last update.

[ポリモーフィズムとは?]具体例で考える

Posted at

こんな人に読んでほしい

  • ポリモーフィズムって言葉は聞いたことがある
  • ググってもイマイチわからない
  • 具体例を出して説明してほしい

具体例

ここはブック○フ。最近は、本も洋服もゲームも売っている。

こことコンビニさえあれば、一生生きていけるなぁ、
そんなことを思っていた矢先、在庫を管理するシステムの設計を任された。

先輩 「まず、在庫の情報を出力するコードをかいてね☆」

さぁ、こんなときどんなコードを書きますか??

ポリモーフィズムを一言でいうと

ポリモーフィズム(多態性)の文字通り、同じメソッド名なのに、
クラスによって実行結果が変わる

今回の例でいうと

Itemを継承しているBook、GameSoft、Clotheにおいて定義したprintメソッドがあり、それを呼び出すと、それぞれの子クラスに合わせて違う結果を返してくれる

情報の整理

  • 在庫(stock)にある商品(item)には全て、title, price, categoryがある
  • 商品の種類は3種類
    • 本(book): 著者(author)の情報がある
    • 洋服(clothe): ブランド(brand)の情報がある
    • ゲーム(gamesoft): どの機種のゲームか(platform)
      という情報がある

継承関係を示す

Book, GameSoft, ClotheはそれぞれItemを継承している
class.png

コードをかいていく

まずはポリモーフィズムを使わない例から

クラス

class Item
    attr_reader :title, :price, :category
    
    def initialize(category, title, price)
        @category = category
        @title = title
        @price = price
    end
end
class Book < Item
    attr_reader :author

    def initialize(category, title, price, author)
        super(category, title, price)
        @author = author
    end
end
class GameSoft < Item
    attr_reader :platform

    def initialize(category, title, price, platform)
        super(category,title, price)
        @platform = platform
    end
end
class Clothe < Item
    attr_reader :brand

    def initialize(category, title, price, brand)
        super(category, title, price)
        @brand = brand
    end
end

データの準備

  • 本には昔から好きな小説
  • ゲームには人生で初めて1000時間以上プレイしたゲーム
  • 洋服はよく行くお店の名前
book_stocks = []
gamesoft_stocks = []
clothe_stocks = []

book_stocks << book = Book.new('ゴールデンスランバー', 980, '伊坂幸太郎')
gamesoft_stocks << gamesoft = GameSoft.new('ドラゴンクエスト8', 4980, 'ps2')
clothe_stocks << clothe = Clothe.new('ネルシャツ', 1980, 'Uniqlo')

データの出力

    book_stocks.each do |book_stock|
        puts "#{book_stock.author}:#{book_stock.title}:#{book_stock.price}"
    # -> 伊坂幸太郎:ゴールデンスランバー:980
    end

    gamesoft_stocks.each do |gamesoft_stock|
        puts "・ゲーム【#{gamesoft_stock.platform}#{gamesoft_stock.title}:#{gamesoft_stock.price}"
    # -> 【ps2】ドラゴンクエスト8:4980
    end

    clothe_stocks.each do |clothe_stock|
        puts "{clothe_stock.brand}-#{clothe_stock.title}:#{clothe_stock.price}"
    # -> Uniqlo-ネルシャツ:1980
    end

次はポリモーフィズムを使う例

クラス

Itemクラスの内容は同じ

class Book < Item
    attr_reader :author

    def initialize(category, title, price, author)
        super(category, title, price)
        @author = author
    end
    # 以下を追記
    def print
        puts "#{@author}:#{@title}:#{@price}"
    end
end
class GameSoft < Item
    attr_reader :platform

    def initialize(category, title, price, platform)
        super(category,title, price)
        @platform = platform
    end
    # 以下を追記
    def print
        puts "【#{@platform}#{@title}:#{@price}"
    end
end
class Clothe < Item
    attr_reader :brand

    def initialize(category, title, price, brand)
        super(category, title, price)
        @brand = brand
    end
    # 以下を追記
    def print
        puts "#{@brand}-#{@title}:#{@price}"
    end
end

データの準備

stocks = []
# データを準備
stocks << Book.new('本', 'ゴールデンスランバー', 980, '伊坂幸太郎')
stocks << GameSoft.new('ゲーム', 'ドラゴンクエスト8', 4980, 'ps2')
stocks << Clothe.new('洋服', 'ネルシャツ', 1980, 'Uniqlo')

データの出力

    # ポリモーフィズムを使うと圧倒的に綺麗に書ける
    stocks.each{|stock| stock.print}

以上で終わります!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0