{ DesignPattern_StatePattern_Sample.dpr
Exemplo de implementação do padrão de projeto State para tratamento de transição de estados de um objeto. Por Rubem Nascimento da Rocha - Manaus, AM OBS.: Pra quem não sabe, Roof é teto e Fan é ventilador! Portanto, RoofFan seria ventilador de teto! } program DesignPattern_StatePattern_Sample; {$APPTYPE CONSOLE} uses SysUtils; type TRoofFan = class; IFanState = interface procedure PullCord(Fan: TRoofFan); end; TFanOff = class(TInterfacedObject, IFanState) protected procedure PullCord(Fan: TRoofFan); end; TFanLowSpeed = class(TInterfacedObject, IFanState) protected procedure PullCord(Fan: TRoofFan); end; TFanMidSpeed = class(TInterfacedObject, IFanState) protected procedure PullCord(Fan: TRoofFan); end; TFanHighSpeed = class(TInterfacedObject, IFanState) protected procedure PullCord(Fan: TRoofFan); end; TRoofFan = class private fState: IFanState; procedure DefineState(State: IFanState); public constructor Create; reintroduce; procedure PullCord; property State: IFanState read fState; end; { TRoofFan } constructor TRoofFan.Create; begin inherited Create; DefineState(TFanOff.Create); end; procedure TRoofFan.DefineState(State: IFanState); begin self.fState := State; end; procedure TRoofFan.PullCord; begin self.fState := nil; self.fState.PullCord(self); end; { TFanHighSpeed } procedure TFanHighSpeed.PullCord(Fan: TRoofFan); begin WriteLn('Velocidade alta...'); Fan.DefineState(TFanOff.Create); end; { TFanMidSpeed } procedure TFanMidSpeed.PullCord(Fan: TRoofFan); begin WriteLn('Velocidade média...'); Fan.DefineState(TFanHighSpeed.Create); end; { TFanLowSpeed } procedure TFanLowSpeed.PullCord(Fan: TRoofFan); begin WriteLn('Velocidade baixa...'); Fan.DefineState(TFanMidSpeed.Create); end; { TFanOff } procedure TFanOff.PullCord(Fan: TRoofFan); begin WriteLn('Desligado.'); Fan.DefineState(TFanLowSpeed.Create); end; var Fan: TRoofFan; begin Fan := TRoofFan.Create; while (True) do Fan.PullCord; end. [As partes desta mensagem que não continham texto foram removidas]