Refactor Gilded Rose to use polymorphic item types

This commit is contained in:
kanaksinghal 2025-06-28 14:29:01 +05:30
parent 58a991fe27
commit 73f09323a8
2 changed files with 68 additions and 30 deletions

0
python/__init__.py Normal file
View File

View File

@ -1,39 +1,26 @@
# -*- coding: utf-8 -*-
class GildedRose(object):
def __init__(self, items):
self.items = items
self.items = [self._create_specific_item(item) for item in items]
def _create_specific_item(self, item):
"""
:param item: Take param as Item object
:return: Specified Item object based on specification.
"""
if item.name.startswith("Aged Brie"):
return AgedBrieItem(item.name, item.sell_in, item.quality)
elif item.name.startswith("Sulfuras"):
return SulfurasItem(item.name, item.sell_in, item.quality)
elif item.name.startswith("Backstage"):
return BackstagePassItem(item.name, item.sell_in, item.quality)
else:
return NormalItem(item.name, item.sell_in, item.quality)
def update_quality(self):
for item in self.items:
if item.name != "Aged Brie" and item.name != "Backstage passes to a TAFKAL80ETC concert":
if item.quality > 0:
if item.name != "Sulfuras, Hand of Ragnaros":
item.quality = item.quality - 1
else:
if item.quality < 50:
item.quality = item.quality + 1
if item.name == "Backstage passes to a TAFKAL80ETC concert":
if item.sell_in < 11:
if item.quality < 50:
item.quality = item.quality + 1
if item.sell_in < 6:
if item.quality < 50:
item.quality = item.quality + 1
if item.name != "Sulfuras, Hand of Ragnaros":
item.sell_in = item.sell_in - 1
if item.sell_in < 0:
if item.name != "Aged Brie":
if item.name != "Backstage passes to a TAFKAL80ETC concert":
if item.quality > 0:
if item.name != "Sulfuras, Hand of Ragnaros":
item.quality = item.quality - 1
else:
item.quality = item.quality - item.quality
else:
if item.quality < 50:
item.quality = item.quality + 1
item.update_quality()
class Item:
@ -44,3 +31,54 @@ class Item:
def __repr__(self):
return "%s, %s, %s" % (self.name, self.sell_in, self.quality)
def update_quality(self):
self.sell_in -= 1
if self.quality > 0:
self.quality -= 1
if self.sell_in < 0 and self.quality > 0:
self.quality -= 1
def _decrease_quality(self, amount=1):
# Setting minimum quality to zero.
self.quality = max(0, self.quality - amount)
def _increase_quality(self, amount=1):
# Setting a limit to 50 as described in spec
self.quality = min(50, self.quality + amount)
class NormalItem(Item):
pass
class AgedBrieItem(Item):
def update_quality(self):
self.sell_in -= 1
self._increase_quality() # It increases in quality as per spec
if self.sell_in < 0:
self._increase_quality() # It increases in quality by double after sell_in passes as per spec
class SulfurasItem(Item):
def update_quality(self):
# It never changes any attributes
pass
class BackstagePassItem(Item):
def update_quality(self):
self.sell_in -= 1
self._increase_quality()
if self.sell_in < 10:
self._increase_quality()
if self.sell_in < 5:
self._increase_quality()
if self.sell_in < 0:
self.quality = 0