AlaaShaker's Weblog

// untitled …

Secret Creator SOLVED [Problem of the Week]

with one comment

After a vigorous week of solutions to this hard problem, I will now post my solution …

The task was to restrict the instantiation of Secret objects only to Creator, and prevent the developer from doing elsewise. Here’s how I did that ..

   1: class Secret
   2: {
   3:     // Private ctor, only local instantiation allowed!
   4:     private Secret() { }
   5:
   6:     // Any class can access this function,
   7:     // but will get only NULL unless it is Creator!
   8:     public static Secret GetSecretInstance()
   9:     {
  10:         // If the caller is Creator, IsCreator should be TRUE ..
  11:         // So returns a new instance of Secret
  12:         if (Creator.IsCreator)
  13:             return new Secret();
  14:         else // another caller, NOT Creator ..
  15:             return null;
  16:     }
  17: }
   1: class Creator
   2: {
   3:     // A static variable that "identifies" the Creator
   4:     // class and allows instantiation of Secret objects
   5:     // if set to TRUE ..
   6:     private static bool isCreator = false;
   7:     // Property : Getter Only!
   8:     public static bool IsCreator { get { return isCreator; } }
   9:
  10:     public Creator() { }
  11:
  12:     public void MyCreatorMethod()
  13:     {
  14:         isCreator = true;   // Unlock ..
  15:         Secret myLocalSecret = Secret.GetSecretInstance();
  16:         isCreator = false;  // Lock it back ..
  17:     }
  18: }

Winners:

  • Mohamed Samy
  • Shady Ahmed El-Yasaki
  • Mohammad Diab

You can check their solutions in the original post.
Thanks to everyone who cared to try solving it, hope you enjoyed that ..
Will try bringing easier ones next time isA 😀

Advertisements

Written by AlaaShaker

August 22, 2008 at 6:47 pm

One Response

Subscribe to comments with RSS.

  1. […] Click her to see the winners list and my solution … Possibly related posts: (automatically generated)Problems with Using xsd.exe to Generate .NET Classes from the FpML XSD Sche…Principles of Object Oriented DesignIf All the World Did Flash Rather than Sudoku – Programming, the Environmen… […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: