State or observer pattern in object C++

3.6k views Asked by At

I am just a bit confused with the difference between the observer and state pattern. I have been given a project where the client is an airplane on a flight which calculates data for different sensor such as GPS,Speed, Fuel level, And then the data is sent over to the network and then to the server. At the moment I have used the observer pattern for my class diagram. The class diagram can be viewed from the below, please let me know if my solution is correct and if the design pattern chosen is good for this solution. Class Diagram

2

There are 2 answers

1
Deb S On

Make a State-event-action automata to define the system( say for error, interlock or some other checking condition etc ) - can use the the state design pattern here. Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically. We use observer design pattern when observable does not know the no of observers and should be able to notify other objects without knowing the objects.

0
Chetan Kinger On

I am just a bit confused with the difference between the observer and state pattern

The Observer pattern is mostly used when you have an object or a set of objects (known as the Observers) that want to be informed/updated about any changes in the state of one or more objects (known as the Observables or Subjects). In your example, the Network is the Observer that wants to know about the changes in the Airplane data. On the other hand, the Airplane data objects such as Speed, GPS etc are the Observable or Subjects that the Network wants to keep a track for changes. (Your terminologies seem to be reversed). Whenever the Airplane data such as its Speed changes, the Network must be notified about this change by the corresponding Speed object.

The State pattern on the other hand is mostly used when your use case can be represented as a finite state machine. In your example, the entire take off, flying and landing process of the Airplane can be represented in a finite state machine with logical states such as landed, taking off, in flight, landing, etc.

It should now be clear that the Observer and State pattern both have a valid application in your case with the Observer pattern being apt for the main problem statement that you have described in your question. That said, there is no need to have seperate Observable objects such as speed, GPS, et.c. You can have a single Observable object called FlighData which has attributes such as speed, GPS, engineFuelLevel, engineTemp etc.

I would also recommend that you get a better understanding of the Observer pattern before you implement it in your application. Here are some links to get started :