This repository has been archived on 2022-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
patterns/state/gumballmachinestate/gumballmachine.d

116 lines
2.1 KiB
D

module gumballmachine;
import std.stdio : writeln;
import std.conv : to;
import soldoutstate, noquarterstate, hasquarterstate, soldstate, state;
class GumballMachine
{
State soldOutState;
State noQuarterState;
State hasQuarterState;
State soldState;
State state;
int count = 0;
this(int numberGumballs)
{
soldOutState = new SoldOutState(this);
noQuarterState = new NoQuarterState(this);
hasQuarterState = new HasQuarterState(this);
soldState = new SoldState(this);
this.count = numberGumballs;
if (numberGumballs > 0)
{
state = noQuarterState;
}
else
{
state = soldOutState;
}
}
void insertQuarter()
{
state.insertQuarter();
}
void ejectQuarter()
{
state.ejectQuarter();
}
void turnCrank()
{
state.turnCrank();
state.dispense();
}
void releaseBall()
{
writeln("A gumball comes rolling out the slot...");
if (count > 0)
{
count = count - 1;
}
}
int getCount()
{
return count;
}
void refill(int count)
{
this.count += count;
writeln("The gumball machine was just refilled; its new count is: ", this.count);
state.refill();
}
void setState(State state)
{
this.state = state;
}
State getState()
{
return state;
}
State getSoldOutState()
{
return soldOutState;
}
State getNoQuarterState()
{
return noQuarterState;
}
State getHasQuarterState()
{
return hasQuarterState;
}
State getSoldState()
{
return soldState;
}
override string toString() const
{
string s;
s ~= "\nMighty Gumball, Inc.";
s ~= "\nJava-enabled Standing Gumball Model #2004";
s ~= "\nInventory: " ~ count.to!string ~ " gumball";
if (count != 1)
{
s ~= "s";
}
s ~= "\n";
s ~= "Machine is " ~ state.to!string ~ "\n";
return s;
}
}