19071711 Design Patterns

|
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
 23 views
of 29

Please download to get full document.

View again

Description
.Net Design Patterns Singleton definition Ensure a class has only one instance and provide a global point of access to it. 1 Design Pattern UML class diagram participants ã o o The classes and/or objects participating in this pattern are: Singleton (LoadBalancer) defines an Instance operation that lets clients access its unique instance. Instance is a class operation. responsible for creating and maintaining its own unique instance. sample code in C# This structural code demonstrates the Si
Share
Tags
Transcript
  .Net Design Patterns Singleton Design Pattern definition Ensure a class has only one instance and provide a global point of access to it. UML class diagramparticipants The classes and/or objects participating in this pattern are: ã Singleton(LoadBalancer) o defines an Instance operation that lets clients access its unique instance. Instance is a class operation. o responsible for creating and maintaining its own unique instance. sample code in C# Thisstructuralcode demonstrates the Singleton pattern which assures only a single instance (the singleton) of the classcan be created.  // Singleton pattern -- Structural exampleusingSystem; namespaceDoFactory.GangOfFour.Singleton.Structural{ /// <summary>  ///MainApp startup class for Structural ///Singleton Design Pattern. /// </summary>  class MainApp { /// <summary>  ///Entry point into console application. /// </summary>  static voidMain() { // Constructor is protected -- cannot use new Singletons1 =Singleton.Instance();  Singletons2 =Singleton.Instance();  // Test for same instance if(s1 == s2){ Console.WriteLine( Objects are the same instance ); } // Wait for user Console.ReadKey();}} /// <summary> ///The 'Singleton' class /// </summary>  class Singleton { private static Singleton_instance;  // Constructor is 'protected' protectedSingleton(){} 1  .Net Design Patterns  public static SingletonInstance() { // Uses lazy initialization. // Note: this is not thread safe. if(_instance ==null) {_instance =new Singleton(); } return_instance;}}} Output Objects are the same instance Thisreal-worldcode demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton)of the class can be created because servers may dynamically come on- or off-line and every request must go throught theone object that has knowledge about the state of the (web) farm.  // Singleton pattern -- Real World exampleusingSystem;usingSystem.Collections.Generic;usingSystem.Threading; namespaceDoFactory.GangOfFour.Singleton.RealWorld{ /// <summary>  ///MainApp startup class for Real-World ///Singleton Design Pattern. /// </summary>  class MainApp { /// <summary>  ///Entry point into console application. /// </summary>  static voidMain() { LoadBalancerb1 =LoadBalancer.GetLoadBalancer();  LoadBalancerb2 =LoadBalancer.GetLoadBalancer();  LoadBalancerb3 =LoadBalancer.GetLoadBalancer();  LoadBalancerb4 =LoadBalancer.GetLoadBalancer();  // Same instance? if(b1 == b2 && b2 == b3 && b3 == b4){ Console.WriteLine( Same instance\n ); } // Load balance 15 server requests LoadBalancerbalancer =LoadBalancer.GetLoadBalancer();  for(inti = 0; i < 15; i++) { stringserver = balancer.Server; Console.WriteLine( Dispatch Request to: + server); } // Wait for user Console.ReadKey();}} /// <summary> 2  .Net Design Patterns  ///The 'Singleton' class /// </summary>  class LoadBalancer { private static LoadBalancer_instance;  private List<string> _servers =new List<string>();  private Random_random =new Random();  // Lock synchronization object private static objectsyncLock =new object();  // Constructor (protected) protectedLoadBalancer(){ // List of available servers_servers.Add( ServerI );_servers.Add( ServerII );_servers.Add( ServerIII );_servers.Add( ServerIV );_servers.Add( ServerV );} public static LoadBalancerGetLoadBalancer() { // Support multithreaded applications through // 'Double checked locking' pattern which (once // the instance exists) avoids locking each // time the method is invoked if(_instance ==null) { lock(syncLock){ if(_instance ==null) {_instance =new LoadBalancer(); }}} return_instance;} // Simple, but effective random load balancer public stringServer { get{ intr = _random.Next(_servers.Count); return_servers[r].ToString();}}}} Output Same instanceServerIIIServerIIServerIServerIIServerIServerIIIServerIServerIIIServerIVServerIIServerII 3  .Net Design Patterns ServerIIIServerIVServerIIServerIV This.NET optimizedcode demonstrates the same code as above but uses more modern, built-in .NET features.Here an elegant .NET specific solution is offered. The Singleton pattern simply uses aprivate constructor and astatic readonlyinstance variable that islazily initialized. Thread safety is guaranteed by the compiler.   // Singleton pattern -- .NET optimizedusingSystem;usingSystem.Collections.Generic; namespaceDoFactory.GangOfFour.Singleton.NETOptimized{ /// <summary>  ///MainApp startup class for .NET optimized ///Singleton Design Pattern. /// </summary>  class MainApp { /// <summary>  ///Entry point into console application. /// </summary>  static voidMain() { LoadBalancerb1 =LoadBalancer.GetLoadBalancer();  LoadBalancerb2 =LoadBalancer.GetLoadBalancer();  LoadBalancerb3 =LoadBalancer.GetLoadBalancer();  LoadBalancerb4 =LoadBalancer.GetLoadBalancer();  // Confirm these are the same instance if(b1 == b2 && b2 == b3 && b3 == b4){ Console.WriteLine( Same instance\n ); } // Next, load balance 15 requests for a server LoadBalancerbalancer =LoadBalancer.GetLoadBalancer();  for(inti = 0; i < 15; i++) { stringserverName = balancer.NextServer.Name; Console.WriteLine( Dispatch request to: + serverName); } // Wait for user Console.ReadKey();}} /// <summary> ///The 'Singleton' class /// </summary>  sealed class LoadBalancer { // Static members are 'eagerly initialized', that is, // immediately when class is loaded for the first time. // .NET guarantees thread safety for static initialization private static readonly LoadBalancer_instance =  new LoadBalancer();  // Type-safe generic list of servers private List<Server> _servers;  private Random_random =new Random(); 4
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks
Ver lista completa de géneros | Spannungswandler 1500 3000 Watt 12V 230V Wechselrichter Softstart CE E8 NEU OVP | Español Castellano