Posts Tagged ‘Design Patterns’

There can be many UI / API / DB level design patterns to follow but when / what to choose need to be carefully decided and following 5 important principals helped to decide on some of the recent decisions … (Thanks to our Chief Architect for providing these guidelines …)

  1. Keep original data
  2. Maintain SVOT – strengths, vulnerabilities, opportunities, threats
  3. Follow KISS – Keep It Simple Silly – easy maintenance / low cost / more reliability
  4. Don’t rely on PUSH
  5. Plan for disaster

Here are the examples of how above principles are helped us to decide between PUSH Vs PULL  &  Filtering out the data or Keeping the original msg …

Our team had created multiple microservices recently for achieving a big org level new initiative. For one of the end to end flow i.e. creating a new app instance for a trail user involves 3 microservices which follows #1, #4 from above principals.

  1. External Service – follows the event lifecycle model where it triggers the subscribed REST endpoint with user request msg when a new user request comes. Here event lifecycle can be synchronous/asynchronous and the service tries multiple times in case when REST endpoint is down. The service also expects REST endpoint to complete the event lifecycle.
  2. REST interface service – gets the msg from external service and pushes it into ZK.
    1. Follows #1 so that the “Original message” been “PUSHed” to  ZK so that it avoids unnecessary parsing/transformations on the msg, operation will be quick & future changes on the msg can be directly synched instead of parsing/editing the zk msg.
    2. Here #4 is not followed since the service been triggered by external service which intern pushes the original message to ZK and it wait for the core service to complete the provisioning and core service updates the status to ZK. Once it gets the provisioning status by following #4 i.e. PULL model  it triggers the external service to complete the event life cycle.
  3. Core service which I owned creates application instances in Docker Swarm for the trail customers based on data provided in Zookeeper (ZK)
    1. Zookeeper out of box provides watch capability where we can watch on a node which triggers an event when changes happen and based on that the core service can take care the provisioning, so it is PUSH model. But here based on #4, we followed the PULL model i.e. pulling ZK data in period interval to take care provisioning requests and it really helped us from single point failure with ZK (i.e. ZK connection failure or missing some of the events due to any exceptions).

 

Design Pattern References:

http://microsoftnlayerapp.codeplex.com/

http://msdn.microsoft.com/es-es/architecture/en/

Define all your functions and variables in the private scope and return an anonymous object at the end of the module with pointers to the private variables and functions you want to reveal as public. Check more @

http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

Ex: Singleton pattern using Revealing Module Pattern

var singleton = function () {
var privateVar = 10;
function privateMethod1() {
return privateVar;
};
function SetVal1(val) {
privateVar = val;
};
function GetVal1() {
return privateVar;
};
function GetVal2() {
return privateMethod1();
};
return {
SetVal1: SetVal1,
GetVal1: GetVal1,
GetVal2: GetVal2
};
} ();

var obj1 = singleton;
var obj2 = singleton;
alert(obj1.GetVal1());
obj1.SetVal1(20);
alert(obj2.GetVal1());

var singleton = function () {
var privateVar = 10;
function privateMethod1() {
return privateVar;
}

return {
SetVal1: function (val) {
privateVar = val;
},
GetVal1: function () {
return privateVar;
},
GetVal2: function () {
return privateMethod1();
}
};
} ();

var obj1 = singleton;
var obj2 = singleton;
alert(obj1.GetVal1());
obj1.SetVal1(20);
alert(obj2.GetVal1());

http://msdn.microsoft.com/en-us/scriptjunkie/hh297451.aspx

http://msdn.microsoft.com/en-US/scriptjunkie/hh273390.aspx

1. Centralized event handling

This will be used in cases where we have a number of similar elements or structures on a page that share similar behaviour when a user-action is performed against them.

In JavaScript, there’s a known bubbling effect in the language so that if an element such as a link or button is clicked, that event is bubbled up to the parent, informing them that something lower down the tree has been clicked. We can use this effect to our advantage.

Ex: In following example we can bind click event to ul and can handle every li click separately with out binding different functions directly to each li. This will also improve performance by minimizing the DOM access for binding/unbinding and by avoiding the event handling for each element separately.

<ul>
 <li class=’one’>One</li>
 <li class=’two’>two</li>
 <li class=’three’>three</li>
 <li class=’four’>four</li>
 <li class=’five’>five</li>
</ul>

stateManager = {
    fly: function () {
        var self = this;
        $(‘ul’).unbind().bind(“click”, function (e) {
            var target = $(e.originalTarget || e.srcElement);
            if (target.is(“li.one”)) {
                self.handleLIOne(target[0]);
            }
            else if (target.is(“li.two”)) {
                self.handleLITwo(target[0]);
            }
        });
    },
    handleLIOne: function (elem) {
        //Do your own implementation for first li element click
        alert(elem.innerHTML);
    },
    handleLITwo: function (elem) {
        //Do your own implementation for second li element click
        alert(elem.innerHTML);
    }
}
stateManager.fly();

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DesignPatterns.PubSub
{
[TestClass]
public class TestSample
{
[TestMethod]
public void Main()
{
Publisher publisherService = new Publisher();
Subscriber1 sub1 = new Subscriber1(publisherService);
Subscriber2 sub2 = new Subscriber2(publisherService);

publisherService.Publish(“Published”);
}
}

public class Publisher
{
public delegate void PublishDelegate(object sender, InfoArgs args);
public event PublishDelegate PublishEvent;

public void OnPublishEvent(object sender, InfoArgs args)
{
if (PublishEvent != null)
PublishEvent(sender, args);
}

public void Publish(string info)
{
OnPublishEvent(this, new InfoArgs(info));
}
}

public class InfoArgs : EventArgs
{
private readonly string info;

public InfoArgs(string info)
{
this.info = info;
}

public string Info
{
get { return info; }
}
}

public class Subscriber1
{
private Publisher publisher;
public Subscriber1(Publisher pPublisher)
{
this.publisher = pPublisher;
pPublisher.PublishEvent += Action;
}

static void Action(object sender, InfoArgs args)
{
Console.WriteLine(“Subscriber1 Action: ” + args.Info);
}
}

public class Subscriber2
{
private Publisher publisher;
public Subscriber2(Publisher pPublisher)
{
this.publisher = pPublisher;
pPublisher.PublishEvent += Action;
}

static void Action(object sender, InfoArgs args)
{
Console.WriteLine(“Subscriber2 Action: ” + args.Info);
}
}
}

Reference –

http://www.akadia.com/services/dotnet_delegates_and_events.html

http://www.dotnetarchitecthouston.com/post/The-Publish-Subscribe-Pattern-in-C-and-some-gotchas.aspx

http://msdn.microsoft.com/en-us/library/ms752254.aspx – WCF

http://msdn.microsoft.com/en-us/library/ff649664.aspx – MS Patterens & Practices



Simple, thread safe and the best performance solution …

public sealed class Singleton
{
    public static readonly Singleton instance = new Singleton();

    Singleton()
    {
    }     
}

  • A single constructor, which is private and parameterless to prevent other classes from creating instance.
  • The class is sealed. It may help the JIT to optimise things.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary – not used in above example and made static variable instance directly public, but for correct use we can have public static property or method to access the instance which will give more control for future
  • Explicit static constructor to tell C# compiler not to mark type as beforefieldinit – not used in above example

There are many ways of creating Singleton object. Refer below link for more details with explanation on each variation …

http://www.yoda.arachsys.com/csharp/singleton.html

1. Using bind, trigger functions we can implement simple Publish/Subscribe pattern in JQuery
2. Below example shows how to create Subscribers (generally the script on page sections or modules) by subscribing to a common custom event called buttonClick through JQuery bind method and it also shows how to publish the custom event on some action (manual or automatic – here on click of button which is manual action) which intern fires all subscriber’s Action methods through JQuery trigger method.
3. There is already a plug-in available in JQuery site for achieving this by simply calling $.subscribe, $.publish and with few other functions. Refer http://www.dotnetoutsource.com/Download/jQuery/Publish-subscribe.aspx for sample. Our custom functions can be extended on top of native JQuery code using Plug-ins to access them directly on $ operator, like $.subscirbe.

<input type=”button” value=”Click Button & Publish Button Click Event” id=”myfield2″/>
<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.js“></script>
<script language=”javascript”>
    // Publisher script can be at page level. Actual publish action will be invoked through either user actions or through callback functions in case of ajax calls
    var Publisher = {
        Publish: function (eventName, args) {
            $(document).trigger(eventName, args);
        }
    };

    // Subscriber1/Subscriber2 can be part of page sections i.e. user controls (in case of asp.net page)
    var Subscriber1 = {
        subscribe: function () {          
            $(document).bind(‘buttonClick’, Subscriber1.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber1 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber1.subscribe();

    var Subscriber2 = {
        subscribe: function () {           
            $(document).bind(‘buttonClick’, Subscriber2.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber2 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber2.subscribe();

    $(document).ready(function () {
        // Binding publish method for button click event
        $(‘#myfield2’).unbind(‘click’).bind(‘click’, function () { Publisher.Publish(‘buttonClick’, [‘1’, ‘2’, ‘3’]); });       
    });
</script>

Following code is a simple example of publish subscriber modal using Javascript. Subscriber1, Subscriber2 are 2 subscribers for an event “PublishOnClick”. User is the publisher who publishes the event by clicking “Click Button & Publish Button Click Event” button. Publisher javascript code provides framework for adding/executing subscribers by different other modules in the same page. For example Subscriber1 can be in one module and Subscriber2 can be in another module and both can subscribe to single button action on the main page.

<input type=”button” value=”Click Button & Publish Button Click Event” id=”myfield2″/>
<script language=”javascript”>
    var Publisher = {
        subscribers: {},       
        Subscribe: function (event, callback) {
            if (Publisher[event] && typeof callback === “function”) {
                if (Publisher.subscribers[event]) {
                    Publisher.subscribers[event].callbacks.push(callback);
                }
                else {
                    Publisher.subscribers[event] = { callbacks: [callback] };
                }
            }
        },
        Publish: function (event, callback) {
            if (Publisher.subscribers[event].callbacks) {
                for (var callback in Publisher.subscribers[event].callbacks) {
                    Publisher.subscribers[event].callbacks[callback].apply(null, arguments);
                }
            }
        },
        // PublishOnClick – name should be same as subscribing event name. Similar to this method we can have different method for each new publishing event
        PublishOnClick: function (event, arguments) {
            Publisher.Publish(event, arguments);
        }
    };

    var Subscriber1 = {
        initialize: function () {
            if (Publisher.Subscribe) {
                Publisher.Subscribe(“PublishOnClick”, Subscriber1.Action);
            }
        },
        Action: function (a, b, c) {
            alert(“Subscriber1 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    };
    Subscriber1.initialize();

    var Subscriber2 = {
        initialize: function () {
            if (Publisher.Subscribe) {
                Publisher.Subscribe(“PublishOnClick”, Subscriber2.Action);
            }
        },
        Action: function (a, b, c) {
            alert(“Subscriber2 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    };
    Subscriber2.initialize();

    var fld2 = document.getElementById(“myfield2”); 
    if (fld2.addEventListener) {
        fld2.addEventListener(“click”, function () { Publisher.PublishOnClick(“PublishOnClick”, [‘1’, ‘2’, ‘3’]); }, false); // publish thru button click event
    }
    else if (fld2.attachEvent) {
        fld2.attachEvent(“onclick”, function () { Publisher.PublishOnClick(“PublishOnClick”, [‘1’, ‘2’, ‘3’]); }); // publish thru button click
    }
</script>