1

I am trying to apply the State Design Pattern to an instant messenger program that I am building. The program is built on top of an existing instant messenger API. I am essentially creating a wrapper class to simplify the process of sending a message. (The wrapper class is going to be used by several automated scripts to fire off messages when some event occurs.)

Here is what I have so far:

  • A Messenger class that will serve as the client interface and hold a reference to the current state.
  • An AbstractMessengerState class from which all of the concrete states will inherit.
  • Several concrete State classes representing the various states (e.g. SessionStarted, LoggedIn, LoggedOut, etc.)

The problem I am having is where to store the state data. That is, which class(es) should store the fields that I need to carry out the business logic of the messenger program. For example, I have a Map data structure that maps userIDs (strings) to the objects used by the underlying API. I have a Session object that is used to access various messenging components and to log in and out of the messenger server. These objects need to be shared between all the subclasses.

If I store this data in the base class than I will be duplicating data every time I instantiate a new State. Is there a way to ensure that the data in the base class is accessible by the subclasses without duplicating the fields?


UPDATED

Ok, after reading a related post I am going to try to store everything in the Context (Messenger) class and see how that goes.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
mooroj
  • 13
  • 5
  • Do you really think applying state pattern would be good here? Try making state diagram and see how many states are there and their transitions. – Atul Jun 18 '13 at 06:32
  • Hi Atul, thanks for the comment. Turns out that the State pattern was not a better solution in this case. It resulted in a lot more code AND added complexity. The sole reason I tried using the State pattern in the first place was to simplify things. My ad-hoc solution -- while far from perfect -- is relatively easier to work with and understand. – mooroj Jun 23 '13 at 19:37

0 Answers0