Skip to content

Commit

Permalink
State
Browse files Browse the repository at this point in the history
  • Loading branch information
georgedem975 committed Aug 6, 2022
1 parent 8478bc3 commit 6931c52
Show file tree
Hide file tree
Showing 5 changed files with 384 additions and 0 deletions.
13 changes: 13 additions & 0 deletions State/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
### State
---
Состояние — поведенческий шаблон проектирования. Используется в тех случаях, когда во время выполнения программы объект должен менять своё поведение в зависимости от своего состояния. Классическая реализация предполагает создание базового абстрактного класса или интерфейса, содержащего все методы и по одному классу на каждое возможно состояние. Шаблон представляет собой частный случай рекомендации «заменяйте условные операторы полиморфизмом».

![Patterns](https://github.com/georgedem975/georgedem975/blob/master/assets/relationships%20between%20classes.png)
![State](https://github.com/georgedem975/georgedem975/blob/master/assets/state.jpg)

---

#### полезные ссылки:
+ [State](https://metanit.com/sharp/patterns/3.6.php)
+ [State](https://www.rsdn.org/article/patterns/State.xml)
+ [State](https://habr.com/ru/post/341134/)
88 changes: 88 additions & 0 deletions State/c#/State.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
abstract class State
{
protected TrafficLight _trafficLight;
public TrafficLight TrafficLight { set => _trafficLight = value; }
public abstract void NextState();
public abstract void PreviousState();
}

class TrafficLight
{
private State _state;

public TrafficLight(State st) => SetState(st);

public void SetState(State st)
{
_state = st;
_state.TrafficLight = this;
}

public void NextState()
{
_state.NextState();
}

public void PreviousState()
{
_state.PreviousState();
}
}

class GreenState : State
{
public override void NextState()
{
Console.WriteLine("from green to yellow");
_trafficLight.SetState(new YellowState());
}

public override void PreviousState()
{
Console.WriteLine("Green color");
}
}

class YellowState : State
{
public override void NextState()
{
Console.WriteLine("from yellow to red");
_trafficLight.SetState(new RedState());
}

public override void PreviousState()
{
Console.WriteLine("from yellow to green");
_trafficLight.SetState(new GreenState());
}
}

class RedState : State
{
public override void NextState()
{
Console.WriteLine("red color");
}

public override void PreviousState()
{
Console.WriteLine("from red to yellow");
_trafficLight.SetState(new YellowState());
}
}

class Program
{
static void Main()
{
TrafficLight trafficLight = new TrafficLight(new GreenState());

trafficLight.NextState();
trafficLight.NextState();
trafficLight.NextState();
trafficLight.PreviousState();
trafficLight.PreviousState();
trafficLight.PreviousState();
}
}
123 changes: 123 additions & 0 deletions State/c++/State.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
#include <iostream>

class TrafficLight;

class State
{
protected:
TrafficLight* trafficLight;

public:
virtual ~State() {}
void SetTrafficLight(TrafficLight* tr);
virtual void nextState() = 0;
virtual void previousState() = 0;
};

class TrafficLight
{
private:
State* state;

public:
TrafficLight(State* st) : state(nullptr)
{
SetState(st);
}
void SetState(State* st);
void nextState();
void previousState();
};

class GreenState : public State
{
public:
void nextState() override;
void previousState() override;
};

class YellowState : public State
{
public:
void nextState() override;
void previousState() override;
};

class RedState : public State
{
public:
void nextState() override;
void previousState() override;
};

int main()
{
TrafficLight* trafficLight = new TrafficLight(new GreenState());

trafficLight->nextState();
trafficLight->nextState();
trafficLight->nextState();
trafficLight->previousState();
trafficLight->previousState();
trafficLight->previousState();

delete trafficLight;

return 0;
}

void State::SetTrafficLight(TrafficLight *tr)
{
trafficLight = tr;
}

void TrafficLight::SetState(State *st)
{
if (state != nullptr) delete state;
state= st;
state->SetTrafficLight(this);
}

void TrafficLight::nextState()
{
state->nextState();
}

void TrafficLight::previousState()
{
state->previousState();
}

void GreenState::nextState()
{
std::cout << "from green to yellow\n";
trafficLight->SetState(new YellowState());
}

void GreenState::previousState()
{
std::cout << "green color\n";
}

void YellowState::nextState()
{
std::cout << "from yellow to red\n";
trafficLight->SetState(new RedState());
}

void YellowState::previousState()
{
std::cout << "from yellow to green\n";
trafficLight->SetState(new GreenState());
}

void RedState::nextState()
{
std::cout << "red color\n";
}

void RedState::previousState()
{
std::cout << "from red to yellow\n";
trafficLight->SetState(new YellowState());
}
85 changes: 85 additions & 0 deletions State/java/State.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
abstract class State{
protected TrafficLight trafficLight;

public void setTrafficLight(TrafficLight trafficLight){
this.trafficLight = trafficLight;
}

public abstract void nextState();

public abstract void previousState();
}

class TrafficLight{
private State state;

public TrafficLight(State st){
setState(st);
}

public void setState(State st){
state = st;
state.setTrafficLight(this);
}

public void nextState(){
state.nextState();
}

public void previousState(){
state.previousState();
}
}

class GreenState extends State{
@Override
public void nextState(){
System.out.println("from green to yellow");
trafficLight.setState(new YellowState());
}

@Override
public void previousState(){
System.out.println("green color");
}
}

class YellowState extends State{
@Override
public void nextState(){
System.out.println("from yellow to red");
trafficLight.setState(new RedState());
}

@Override
public void previousState(){
System.out.println("from yellow to green");
trafficLight.setState(new GreenState());
}
}

class RedState extends State{
@Override
public void nextState(){
System.out.println("red color");
}

@Override
public void previousState(){
System.out.println("from red to yellow");
trafficLight.setState(new YellowState());
}
}

public class Main {
public static void main(String[] args){
TrafficLight trafficLight = new TrafficLight(new GreenState());

trafficLight.nextState();
trafficLight.nextState();
trafficLight.nextState();
trafficLight.previousState();
trafficLight.previousState();
trafficLight.previousState();
}
}
75 changes: 75 additions & 0 deletions State/python/State.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import abc


class State(metaclass=abc.ABCMeta):

def __init__(self):
self._traffic_light: 'TrafficLight' = None

@abc.abstractmethod
def next_state(self):
pass

@abc.abstractmethod
def previous_state(self):
pass


class TrafficLight:

def __init__(self, st: State):
self.__state = None
self.set_state(st)

def set_state(self, st: State):
self.__state = st
self.__state._traffic_light = self

def next_state(self):
self.__state.next_state()

def previous_state(self):
self.__state.previous_state()


class GreenState(State):

def next_state(self):
print('from green to yellow')
self._traffic_light.set_state(YellowState())

def previous_state(self):
print('Green color')


class YellowState(State):

def next_state(self):
print('from yellow to red')
self._traffic_light.set_state(RedState())

def previous_state(self):
print('from yellow to green')
self._traffic_light.set_state(GreenState())


class RedState(State):

def next_state(self):
print('red color')

def previous_state(self):
print('from red to yellow')
self._traffic_light.set_state(YellowState())


if __name__ == '__main__':

traffic_light = TrafficLight(GreenState())

traffic_light.next_state()
traffic_light.next_state()
traffic_light.next_state()
traffic_light.previous_state()
traffic_light.previous_state()
traffic_light.previous_state()

0 comments on commit 6931c52

Please sign in to comment.