Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
boring right State pattern solution in Clear category for Multicolored Lamp by roman.bratishchev
from itertools import cycle
from typing import Self
class StateMeta(type):
def __new__(self,lclass:str,bases:tuple,attrs:dict,**kwargs) -> Self:
if 'color' in kwargs: attrs['_color']=kwargs['color']
return super().__new__(self, lclass, bases, attrs)
class State(metaclass=StateMeta): glow=lambda self: self._color
# state classes
class GState(State,color='Green'): pass
class RState(State,color='Red'): pass
class BState(State,color='Blue'): pass
class YState(State,color='Yellow'): pass
# context switches the states and delegates
class Lamp:
def __init__(self) -> None: self.states=cycle((GState(),RState(),BState(),YState()))
def light(self) -> str: return next(self.states).glow()
if __name__ == "__main__":
# These "asserts" using only for self-checking and not necessary for auto-testing
lamp_1 = Lamp()
lamp_2 = Lamp()
lamp_1.light() # Green
lamp_1.light() # Red
lamp_2.light() # Green
assert lamp_1.light() == "Blue"
assert lamp_1.light() == "Yellow"
assert lamp_1.light() == "Green"
assert lamp_2.light() == "Red"
assert lamp_2.light() == "Blue"
print("Coding complete? Let's try tests!")
Sept. 30, 2024
Comments: