State and FlyWeight patterns

1k views Asked by At

Can anybody share example of using state pattern with flyweight pattern (flyweight pattern is for creating state objects to save memory)?

UPDATE: How to use a combination of state and fw patterns?

2

There are 2 answers

6
Peter Lawrey On BEST ANSWER

Autoboxing uses the flyweight pattern to minimise object creation (for small values of Integer)

e.g. for Boolean and Byte all possible values are cached.

Java uses states for many components, however a state machine also includes functionality switched by state.

Here is an example I wrote using enum http://vanillajava.blogspot.com/2011/06/java-secret-using-enum-as-state-machine.html

0
jgauffin On

I usually use state pattern to avoid conditional statements.

instead of using:

switch (state)
{
    case ParserState.BeforeMethod:
        //do some processing
        break;
    case ParserState.InMethod:
        //do some processing
        break;
}

I can just write:

currentState = currentState.process(context);

A sample class can look like

public class SomeClass : ParserState
{
    public ParserState process(IParserContext context)
    {
       //do some proceccing

       if (m_completed)
           return new SomeOtherState();

       return this;
    }

}

i.e. The logic is moved to small classes which are used to handle a specific state. So you get two things:

  • Smaller classes with clear responsibilities
  • Less conditional statements = more readable code.