Skip to content

Instantly share code, notes, and snippets.

@ytnk531
Created May 7, 2021 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytnk531/e520e636eba8d9ed6bb43e788feea150 to your computer and use it in GitHub Desktop.
Save ytnk531/e520e636eba8d9ed6bb43e788feea150 to your computer and use it in GitHub Desktop.
# ItemProxyはItemImplと同じくprice()とprint_self()を公開する。rubyは共 通のインターフェースを強制するようなスタイルのコーディングはしないので 特に何も書かない。
class ItemImpl
attr_reader :price
def initialize(price)
@price = price
end
def print_self
puts "This item is #{price} yen."
end
end
# 毎回DBアクセスすることになるので無駄があるが、趣旨とずれるので特に考 慮しない
class ItemProxy
def initialize(item_id)
@item_id = item_id
@db = Database.new
end
def price
resp = @db.query("SELECT price from items where id = #{@item_id};").to_i
end
def print_self
item.print_self
end
def item
ItemImpl.new(price)
end
end
class Database
def query(query_string)
# 本来はDBアクセスしてクエリを発行して結果を返す処理をする
"500"
end
end
impl = ItemImpl.new(400)
proxy = ItemProxy.new(10)
impl.print_self
proxy.print_self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment