Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flyweight [Design Pattern]
#4
It's worth to mention that this design pattern can be implemented to the existing code.
The current example (made by me) isn't showing this way, so i'm going to demonstrate one neat trick with use of metatables that allows us to easilly edit the existing class to use the flyweight pattern. Suppose that we have a class called Npc, let's just assume that it looks like more or less like this:

Squirrel Script
  1. class Npc
  2. {
  3. _maxHealth = 40
  4. _maxMana = 10
  5. // more fields and some methods & constructor.
  6. }



The problem is, that if we change this class by adding the static keyword before the attributes like this:

Squirrel Script
  1. class Npc
  2. {
  3. static _maxHealth = 40
  4. static _maxMana = 10
  5. // more fields and some methods & constructor.
  6. }



The error will occure when we try to get the static field via the object like this:

Squirrel Script
  1. local npc = Npc(...) // ... means some arguments
  2. print(npc._maxMana)



What we can do, is to add the _get metamethod which will be invoked each time, when we try to access the object field which doesn't exists.

Squirrel Script
  1. class Npc
  2. {
  3. static _maxHealth = 40
  4. static _maxMana = 10
  5.  
  6.  
  7. function _get(idx)
  8. {
  9. try
  10. return getclass()[idx]
  11. catch (msg)
  12. throw null
  13. }
  14. }



Now, when we try to access the field via the object, everything will be working as it should.
There is only one problem, having a static fields as types: int, string, null, bool, float will cause a problem with directly trying to modify them.
First of all, we can't modify the static field via the object, even if we provide the _set metamethod, it will still raise an error.
There is a way to add the desired functionallity by using the class.newmember or class.rawnewmember.

Squirrel Script
  1. class Npc
  2. {
  3. static _maxHealth = 40
  4. static _maxMana = 10
  5.  
  6.  
  7. function _get(idx)
  8. {
  9. try
  10. return getclass()[idx]
  11. catch (msg)
  12. throw null
  13. }
  14.  
  15. function _set(idx, val)
  16. {
  17. try
  18. getclass().newmember(idx, val, "", true)
  19. catch (msg)
  20. throw null
  21. }
  22. }



IMO however it's not required to supply the _set metamethod. Anyways, that's all i wanted to show, ofc _get metamethod can be implemented in different way allowing us to access the data from for example a table.
Reply


Messages In This Thread
Flyweight [Design Pattern] - by Quarchodron - 11.02.2019, 10:53
RE: Flyweight [Design Pattern] - by Patrix - 11.02.2019, 14:26
RE: Flyweight [Design Pattern] - by Patrix - 16.09.2019, 20:32

Possibly Related Threads…
Thread Author Replies Views Last Post
  Decorator [Design Pattern] Patrix 1 2,712 10.09.2019, 07:56
Last Post: Quarchodron

Forum Jump:


Users browsing this thread: 1 Guest(s)