CSharp mimicking JavaScript design pattern

Simplest C# code so far I can think of equivalent to the JavaScript design pattern to allow private members.

The original JavaScript code can be found here:

http://www.crockford.com/javascript/private.html

For the ease of comparison, the JavaScript code from the above link is also pasted here,

 1 function Container(param) {
 2 
 3     function dec() {
 4         if (secret > 0) {
 5             secret -= 1;
 6             return true;
 7         } else {
 8             return false;
 9         }
10     }
11 
12     this.member = param;
13     var secret = 3;
14     var that = this;
15 
16     this.service = function () {
17         return dec() ? that.member : null;
18     };
19 }

Following is the equivalent C# code,

class Program
{
    class Container
    {
        // delegates
        delegate bool JsPrivateDelegate();
        public delegate dynamic ServiceDelegate();

        // constructor
        public Container(dynamic param)
        {
            var secret = 3;
            JsPrivateDelegate dec = delegate()
                {
                    if (secret <= 0) return false;
                    secret--;
                    return true;
                };
            Member = param;
            Service = () => dec() ? Member : null;
        }

        public dynamic Member { get; private set; } // public property
        public ServiceDelegate Service { get; private set; }    // public 'method'
    }
    
    static void Main(string[] args)
    {
        var c = new Container("haha");
        dynamic s;
        do
        {
            s = c.Service();    // consumes the service
            Console.WriteLine("{0}", s ?? "<null>");
        } while (s != null);
    }
}

Note the main point is make private members local variables as long as possible since they are accessible from the closure which C# fully supports. However as a strong-typed language, C# can't get rid of the delegate definition and the local variable definition needs to be in order within a method ('secret' has to come before 'dec').

posted @ 2013-05-21 18:12  quanben  阅读(223)  评论(0编辑  收藏  举报