简体   繁体   中英

State design pattern - Passing Objects

I have a state design pattern implementation with 3 states:

State1::DoTask(){...}

State2::DoTask(){...}

State3::DoTask(){...}

These all 3 states need to use 2 classes already instanced

eg

State1::DoTask()
{ 
    sensor->GetData(...)
    server->Send(buf,size)
}

How is the best way to pass these 2 class pointer objects to the State1, State2 and State3?

I thought in two options:

1) The Sensor and Server class could be a singleton:

State1::DoTask()
{
    sensor = Sensor::GetInstance();
    server = Server::GetInstance();
    ....
}

2) Passing by using other object to hold the class pointer:

class ComClasses
{
    Sensor *sensor;
    Server *server;
}

State1::DoTask(ComClasses *c)
{
    ....
}

In your opinion, how is the best method? Is there a better solution?

Best regards,

You could also do it when you initialize the states.

State1 state1( sensor, server );
State2 state2( sensor, server );
State3 state3( sensor, server );

And then the DoTask interface method, which is your client method, should not care about the implementation of each individual State class. Each state will implement it using their own information.

state1.DoTask();
...

To comment on your solutions, I think I'd prefer the singleton. If you find a new object that needs to be used by each state you will probably keep adding parameters. Your second solution solves that but you will then, maybe, pass objects to states that won't need to use them.

But probably initialization is best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM