Search code examples
design-patternsstate-pattern

Should I apply state pattern here?


I have a panel that draws alot of things. To make drawing effecient I am using a BufferedImage so that I dont have to draw everything, everytime something happens.

My paintComponent only has to 'if' statements:

if(!extraOnly) //paint something

paint something

if(listener.getRectangle() != null) // Paint something

I like the idea of using state pattern, but I am not sure its the right moment to use it? I don't like the idea of having to set a boolean for extraOnly and maybe there has also gotten pattern fever in me :). Each state would only have one method, draw(Graphics g)

Since this is the view part of my application in a MVC pattern, I am also unsure of using state pattern is wrong. Shouldn't state be part of the model and not the view?


Solution

  • I see nothing wrong with having state in the view. This is clearly not the same state as in the model though.

    An example would be a webbrowser. The model in this case is the web page DOM and the browser view is rendering the DOM into a screen presentation. While scrolling down the web page it would be very inefficient to do render the DOM on each frame. Clearly a buffered state is the solution to this. The state would only have to be updated if the underlying DOM is changed.