3

I have an example which demonstrates flyweight design pattern, where there are soldiers in a game. This soldier instance has to be used by multiple clients simultaneously. And thislink says the same object is returned if it is available in the map (or cache). Isn't this unsafe to use same object concurrently as a thread may change its property.

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
jayendra bhatt
  • 1,337
  • 2
  • 19
  • 41
  • 1
    If soldiers are not thread-safe, then the design is broken. – Marko Topolnik Mar 18 '15 at 11:04
  • 1
    Each solider is a `SoldierClient`. The `SoldierClient` stores the modifiable state of each soldier - that isn't shared, so can be as thread-unsafe as it wants. The only bit that **is** shared is the `SoldierImp`. This contains code for drawing a soldier, and routines for moving a soldier around. These should definitely be thread-safe and stateless. – David Lavender Mar 18 '15 at 11:08

1 Answers1

4

Yes. A flyweight pattern should only be used with immutable objects, regardless whether it is used in a single thread or in a multi-thread environment.

Thomas Stets
  • 3,015
  • 4
  • 17
  • 29