-
-
Save ledsun/4943910 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
module Movable | |
attr_reader :position | |
def set_position(position) | |
@position = position.is_a?(Movable) ? position.position : position | |
end | |
def set_ratio(x, y) | |
@x_ratio = x | |
@y_ratio = y | |
end | |
def move(direction) | |
case direction | |
when :up | |
@position[:y] -= 10 * @y_ratio | |
when :down | |
@position[:y] += 10 * @y_ratio | |
when :left | |
@position[:x] -= 10 * @x_ratio | |
when :right | |
@position[:x] += 10 * @x_ratio | |
end | |
end | |
end | |
class NormalPlayer | |
include Movable | |
def initialize(position) | |
set_position position | |
set_ratio 1, 1 | |
end | |
end | |
class FastPlayer | |
include Movable | |
def initialize(position) | |
set_position position | |
set_ratio 2, 2 | |
end | |
end | |
class KaniPlayer | |
include Movable | |
def initialize(position) | |
set_position position | |
set_ratio 4, 0.5 | |
end | |
end | |
player = NormalPlayer.new :x => 100, :y => 100 | |
player.move :up | |
p player.position # => {:x => 100, :y => 90} | |
player = FastPlayer.new player | |
player.move :down | |
p player.position #=> {:x => 100, :y => 110} | |
player = KaniPlayer.new player | |
player.move :up | |
player.move :left | |
p player.position #=> {:x => 60, :y => 105} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
こんどこそModuleを使ってみた。抽象クラスっぽい感じ?
委譲より多重継承だよね。なんちゃって