CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Threaded View

  1. #7
    Join Date
    Nov 2003
    Posts
    1,405

    Re: Flyweight Pattern

    Quote Originally Posted by Abalfazl View Post
    Which data in these objects iin this example are similar that he share?
    In that example whole Time objects are shared.

    Time objects are not created using new directly. Instead a factory method is called. The factory method keeps track of all Time objects it creates. If a specific Time object already has been created before, the factory method returns a reference to this existing object rather than creating a new one. So if you do,

    Time t1 = TimeFactory.create(12, 50);
    Time t2 = TimeFactory.create(12, 50);

    the factory method (called create) will make sure both t1 and t2 refers to the same object. So t1==t2 will be true. This is the Flyweight sharing.

    Note that String literals are treated according to the same principle. If you do,

    String s1 = "hello";
    String s2 = "hello";

    Then both s1 and s2 will refer to the same String object. So s1==s2 will be true.

    Also note that this kind of Flyweight sharing requires objects to be immutable (after creation the object state cannot be changed).
    Last edited by _uj; January 13th, 2009 at 06:35 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured