Labels

Tuesday, November 16, 2010

Bridge Design Pattern - Structural

1.1          Intent

Decouple an abstraction from its implementation so that the two can vary independently.
Also known as Handle/Body.

1.2          Motivation

·         Usually we use inheritance to accommodate an abstraction that can have one of several possible implementations.
·         An abstract class defines the interface to the abstraction, and concrete subclasses implement it in different ways.
·         But this approach isn't always flexible enough.
·         Inheritance binds an implementation to the abstraction permanently, making it difficult to modify, extend, and reuse abstractions and implementations independently.



Consider implementing a portable Window abstraction in a user interface toolkit. This abstraction should enable us to write applications that work on both the X Window System and IBM's Presentation Manager (PM), for example. Using inheritance, we could
define an abstract class Window and subclasses XWindow and PMWindow that implement the Window interface for the different platforms. But this approach has two drawbacks:
1. It's inconvenient to extend the Window abstraction to cover different kinds of windows or new platforms. Imagine an IconWindow subclass of Window that specializes the Window abstraction for icons. To support IconWindows for both platforms, we have to implement two new classes, XIconWindow and PMIconWindow. Worse, we'll have to define two classes for every kind of window. Supporting a third platform requires yet another new Window subclass for every kind of window.
2. It makes client code platform-dependent. Whenever a client creates a window, it instantiates a concrete class that has a specific implementation. This, in turn, makes it harder to port the client code to other platforms.

1.3          Structure





1.4          Participants

 The classes and/or objects participating in this pattern are:

Abstraction   
·       Defines the abstraction's interface.
·       Maintains a reference to an object of type Implementor.

RefinedAbstraction   
extends the interface defined by Abstraction.

Implementor   
defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.

ConcreteImplementor   
implements the Implementor interface and defines its concrete implementation.

1.5          Applicability

Use the Bridge pattern when:
·         you want to avoid a permanent binding between an abstraction and its implementation, for example, when the implementation must be selected or switched at run-time.
·         both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
·         changes in the implementation of an abstraction should have no impact on clients; i.e. their code should not have to be recompiled.
·         you want to hide the implementation of an abstraction completely from clients.
·         you have a proliferation of classes; such a class hierarchy indicates the need for splitting an object into two parts.

1.6          Consequences

The Bridge pattern is intended to keep the interface to your client program constant while allowing you to change the actual kind of class you display or use. This can prevent you from recompiling a complicated set of user interface modules and only require that you recompile the bridge itself and the actual end display class.

You can extend the implementation class and the Bridge class separately, and usually without much interaction with each other.
You can hide implementation details from the client program much more easily.

1.7          Sample Code

This code demonstrates the Bridge pattern which separates (decouples) the interface from its implementation. The implementation can evolve without changing clients which use the abstraction of the object.


class Abstraction
  {
    public  Implementor implementor;

    public virtual void Operation()
    {
      implementor.Operation();
    }
  }
class RefinedAbstraction : Abstraction
  {
    public override void Operation()
    {
      implementor.Operation();
    }
  }


abstract class Implementor
  {
    public abstract void Operation();
  }

class ConcreteImplementorA : Implementor
  {
    public override void Operation()
    {
      Console.WriteLine("ConcreteImplementorA ");
    }
  }
class ConcreteImplementorB : Implementor
  {
    public override void Operation()
    {
      Console.WriteLine("ConcreteImplementorB ");
    }
  }




class MainApp
  {
    static void Main()
    {
      Abstraction ab = new RefinedAbstraction();

      // Set implementation and call
      ab.Implementor = new ConcreteImplementorA();
      ab.Operation();

      // Change implemention and call
      ab.Implementor = new ConcreteImplementorB();
      ab.Operation();   
   }
  }

Output –

ConcreteImplementorA Operation
ConcreteImplementorB Operation

1.8          Sample Code2

This real-world code demonstrates the Bridge pattern in which a BusinessObject abstraction is decoupled from the implementation in DataObject. The DataObject implementations can evolve dynamically without changing any clients.





using System;
using System.Collections;

namespace Xpanxion.Bridge.RealWorld
{

    // MainApp test application

    class MainApp
    {
        static void Main()
        {
            // Create RefinedAbstraction
            Customers customers =
              new Customers("Chicago");

            // Set ConcreteImplementor
            customers.Data = new CustomersData();

            // Exercise the bridge
            customers.Show();
            customers.Next();
            customers.Show();
            customers.Next();
            customers.Show();
            customers.New("Henry Velasquez");

            customers.ShowAll();

            // Wait for user
            Console.Read();
        }
    }

    // "Abstraction"

    class CustomersBase
    {
        private DataObject dataObject;
        protected string group;

        public CustomersBase(string group)
        {
            this.group = group;
        }

        // Property
        public DataObject Data
        {
            set { dataObject = value; }
            get { return dataObject; }
        }

        public virtual void Next()
        {
            dataObject.NextRecord();
        }

        public virtual void Prior()
        {
            dataObject.PriorRecord();
        }

        public virtual void New(string name)
        {
            dataObject.NewRecord(name);
        }

        public virtual void Delete(string name)
        {
            dataObject.DeleteRecord(name);
        }

        public virtual void Show()
        {
            dataObject.ShowRecord();
        }

        public virtual void ShowAll()
        {
            Console.WriteLine("Customer Group: " + group);
            dataObject.ShowAllRecords();
        }
    }

    // "RefinedAbstraction"

    class Customers : CustomersBase
    {
        // Constructor
        public Customers(string group)
            : base(group)
        {
        }

        public override void ShowAll()
        {
            // Add separator lines
            Console.WriteLine();
            Console.WriteLine("------------------------");
            base.ShowAll();
            Console.WriteLine("------------------------");
        }
    }

    // "Implementor"

    abstract class DataObject
    {
        public abstract void NextRecord();
        public abstract void PriorRecord();
        public abstract void NewRecord(string name);
        public abstract void DeleteRecord(string name);
        public abstract void ShowRecord();
        public abstract void ShowAllRecords();
    }

    // "ConcreteImplementor"

    class CustomersData : DataObject
    {
        private ArrayList customers = new ArrayList();
        private int current = 0;

        public CustomersData()
        {
            // Loaded from a database
            customers.Add("Jim Jones");
            customers.Add("Samual Jackson");
            customers.Add("Allen Good");
            customers.Add("Ann Stills");
            customers.Add("Lisa Giolani");
        }

        public override void NextRecord()
        {
            if (current <= customers.Count - 1)
            {
                current++;
            }
        }

        public override void PriorRecord()
        {
            if (current > 0)
            {
                current--;
            }
        }

        public override void NewRecord(string name)
        {
            customers.Add(name);
        }

        public override void DeleteRecord(string name)
        {
            customers.Remove(name);
        }

        public override void ShowRecord()
        {
            Console.WriteLine(customers[current]);
        }

        public override void ShowAllRecords()
        {
            foreach (string name in customers)
            {
                Console.WriteLine(" " + name);
            }
        }
    }
}




1.9          Bridge Design Pattern in .NET

Windows forms as Bridges

The .NET visual control is itself an ideal example of a Bridge pattern implementation. A Control is a reusable software component that can be manipulated visually in a builder tool. The entire C# Controls support a query interface that enables builder programs to enumerate their properties and display them for easy modification. Figure below is a screen from Visual Studio.NET displaying a panel with a text field and a check box. The builder panel to the right shows how you can modify the properties of either of those components using a simple visual interface.



In other words, all ActiveX controls have the same interface used by the Builder program, and you can substitute any control for any other and still manipulate its properties using the same convenient interface. The actual program you construct uses these classes in a conventional way, each having its own rather different methods, but from the builder's point of view, they all appear to be the same.

Database Drivers as Bridges

A driver is an object that operates a computer system or an external device according to a well-specified interface. Drivers provide the most common example of the Bridge pattern.
Applications that use drivers are abstractions. The effect of running the application depends on which driver is in place. Each driver is an instance of the Adapter pattern, providing the interface a client expects using the services of a class with a different interface. An overall design that uses drivers is an instance of Bridge [4]. The design separates application development from the development of the drivers that implement the abstract operations on which the applications rely. A driver-based design forces us to create a common, abstract model of the machine or system that will be driven. This has the advantage of letting code on the abstraction side apply to any of the drivers that it might execute against. Defining a common set of methods for the drivers may also incur the disadvantage of eliminating behavior that one driver entity might support.

These tradeoffs in having a broad or narrow interface in an implementation of Bridge also appear in database drivers. For eg., in .NET, we can use the OledbDataReader class to work with almost any database, including SQL Server. However, .NET also provides SqlDataReader that works only with SQL server and is faster than the OleDbDataReader. In addition, the SqlDataReader class offers methods that the OleDbDataReader class does not, such as the GetSqlMoney() method.

Adaptive Rendering Functionality – ASP.NET Server Controls as Bridges

In the .NET Framework Version 2.0, ASP.NET provides a unified control architecture that enables a single set of server controls to work with many different browsers for desktop and  obile devices. This functionality is made possible by pluggable adapter classes, which render markup based on the capabilities of the browser that accesses a page.

In the earlier versions of .NET Framework, ASP.NET mobile Web Forms pages were created using mobile controls. These controls implemented rendering for mobile-device browsers and were distinct from the set of standard ASP.NET server controls. In the new ASP.NET adaptive rendering architecture [16], a separate set of mobile controls does not exist. ASP.NET server controls encapsulate core user interface logic and provide default rendering, which is HTML for desktop browsers. Rendering for other browsers is provided by separate adapter classes, which are not controls. Adapters bind to controls at run time and adapt the output of controls to the requesting browser. Adapters call markup writer classes for creating WML, XHTML, cHTML, and other kinds of markup. Mappings between controls and adapters are specified in configuration files.

An important feature of adapters is that they operate behind the scenes without any work on the part of the page developer. A page developer can use a control without any knowledge of adapters, assuming that the control itself adapts its rendering for different browsers. The ASP.NET page framework enables page developers to use filters to customize control properties for different browsers and devices.

Hope this helps.

Thanks & Regards,
Arun Manglick

Adapter Design Pattern: Structural

1.1          Definition


The Adapter design pattern (sometimes referred to as the Wrapper Pattern or simply a Wrapper) 'adapts' one interface for a class into another that a client expects.
An adapter allows classes to work together that normally could not because of incompatible interfaces by wrapping its own interface around that of an already existing class.

The Adapter pattern maps the interface of one class onto another so that they can work together. These incompatible classes may come from different libraries or frameworks.

There are two types of adapter patterns:

·         The Object Adapter pattern - In this type of adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to a physical instance of the wrapped object.



·         The Class Adapter pattern - This type of adapter uses multiple inheritance to achieve its goal. The adapter is created inheriting interfaces from both the interface that is expected and the interface that is pre-existing. This pattern is less often used as some popular languages, such as C#, Java, do not support true multiple inheritance as the designers of these languages consider it a dangerous practice.



The adapter pattern is useful in situations where an already existing class provides some or all of the services you need but does not use the interface you need. A good real life example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed. 

1.1          Intent

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
For instance, if multiple boolean values are stored as a single integer but your consumer requires a 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value.

1.2          Motivation

  • Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application.
  • We can not change the library interface, since we may not have its source code.
  • Even if we did have the source code, we probably should not change the library for each domain-specific application

1.3          Applicability

  • You want to use an existing class, and its interface does not match the one you need.
  • You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces.

1.4          Structure



1.5          Participants

The classes and/or objects participating in this pattern are:

  •  Target   (ChemicalCompound)
    • defines the domain-specific interface that Client uses.
  •  Adapter   (Compound)
    • adapts the interface Adaptee to the Target interface.
  •  Adaptee   (ChemicalDatabank)
    • defines an existing interface that needs adapting.
  •  Client   (AdapterApp)
    • collaborates with objects conforming to the Target interface.

1.6          Sample Code

This code demonstrates the Adapter pattern which maps the interface of one class onto another so that they can work together. These incompatible classes may come from different libraries or frameworks.




using System;

namespace Xpanxion.Adapter
{

    class MainApp
    {
        static void Main()
        {
            Target target = new Adapter();
            target.Request();
            Console.Read();
        }
    }

    class Target
    {
        public virtual void Request()
        {
            Console.WriteLine("Called Target Request()");
        }
    }

    class Adapter : Target
    {
        private Adaptee adaptee = new Adaptee();

        public override void Request()
        {
            adaptee.SpecificRequest();
        }
    }

    class Adaptee
    {
        public void SpecificRequest()
        {
            Console.WriteLine("Called SpecificRequest()");
        }
    }
}



1.7          Sample Code2

This real-world code demonstrates the use of a legacy chemical databank. Chemical compound objects access the databank through an Adapter interface.




namespace Xpanxion.Adapter2
{
    class MainApp
    {
        static void Main()
        {
            // Non-adapted chemical compound
            Compound stuff = new Compound("Unknown");
            stuff.Display();

            // Adapted chemical compounds
            Compound water = new RichCompound("Water");
            water.Display();

            Compound benzene = new RichCompound("Benzene");
            benzene.Display();

            Compound alcohol = new RichCompound("Alcohol");
            alcohol.Display();

            // Wait for user
            Console.Read();
        }
    }

    // "Target"

    class Compound
    {
        protected string name;
        protected float boilingPoint;
        protected float meltingPoint;
        protected double molecularWeight;
        protected string molecularFormula;

        // Constructor
        public Compound(string name)
        {
            this.name = name;
        }

        public virtual void Display()
        {
            Console.WriteLine("\nCompound: {0} ------ ", name);
        }
    }

    // "Adapter"

    class RichCompound : Compound
    {
        private ChemicalDatabank bank;

        // Constructor
        public RichCompound(string name)
            : base(name)
        {
        }

        public override void Display()
        {
            // Adaptee
            bank = new ChemicalDatabank();
            boilingPoint = bank.GetCriticalPoint(name, "B");
            meltingPoint = bank.GetCriticalPoint(name, "M");
            molecularWeight = bank.GetMolecularWeight(name);
            molecularFormula = bank.GetMolecularStructure(name);

            base.Display();
            Console.WriteLine(" Formula: {0}", molecularFormula);
            Console.WriteLine(" Weight : {0}", molecularWeight);
            Console.WriteLine(" Melting Pt: {0}", meltingPoint);
            Console.WriteLine(" Boiling Pt: {0}", boilingPoint);
        }
    }

    // "Adaptee"

    class ChemicalDatabank
    {
        // The Databank 'legacy API'
        public float GetCriticalPoint(string compound, string point)
        {
            float temperature = 0.0F;

            // Melting Point
            if (point == "M")
            {
                switch (compound.ToLower())
                {
                    case "water": temperature = 0.0F; break;
                    case "benzene": temperature = 5.5F; break;
                    case "alcohol": temperature = -114.1F; break;
                }
            }
            // Boiling Point
            else
            {
                switch (compound.ToLower())
                {
                    case "water": temperature = 100.0F; break;
                    case "benzene": temperature = 80.1F; break;
                    case "alcohol": temperature = 78.3F; break;
                }
            }
            return temperature;
        }

        public string GetMolecularStructure(string compound)
        {
            string structure = "";

            switch (compound.ToLower())
            {
                case "water": structure = "H20"; break;
                case "benzene": structure = "C6H6"; break;
                case "alcohol": structure = "C2H6O2"; break;
            }
            return structure;
        }

        public double GetMolecularWeight(string compound)
        {
            double weight = 0.0;
            switch (compound.ToLower())
            {
                case "water": weight = 18.015; break;
                case "benzene": weight = 78.1134; break;
                case "alcohol": weight = 46.0688; break;
            }
            return weight;
        }
    }
}


OutPut:

Compound: Unknown ------

Compound: Water ------
 Formula: H20
 Weight : 18.015
 Melting Pt: 0
 Boiling Pt: 100

Compound: Benzene ------
 Formula: C6H6
 Weight : 78.1134
 Melting Pt: 5.5
 Boiling Pt: 80.1

Compound: Alcohol ------
 Formula: C2H6O2
 Weight : 46.0688
 Melting Pt: -114.1
 Boiling Pt: 78.3


1.8          Adaptor in .NET

One of the strengths of the .NET Framework is backward compatibility. From .NET-based code you can easily call legacy COM objects and vice versa. In order to use a COM component in your project, all you have to do is add a reference to it via the Add Reference dialog in Visual Studio .NET. Behind the scenes, Visual Studio® .NET invokes the tlbimp.exe tool to create a Runtime Callable Wrapper (RCW) class, contained in an interop assembly. Once the reference has been added (and the interop assembly has been generated for you), the COM component can be used like any other class in managed code. If you were looking at code someone else had written without seeing the list of references (and without examining metadata associated with the classes or their implementation), you would be unable to tell which classes were written in a .NET-targeted language and which were COM components.

The magic that makes this happen is contained in the RCW. COM components have different error handling mechanisms and also make use of different data types. For example, strings in the .NET Framework use the System.String class while COM might use a BSTR. When calling a COM component with a string parameter from .NET-based code, though, you can pass in a System.String just like you would to any other similar managed code method. Inside the RCW, this System.String is converted into a format that the COM component expects, like a BSTR, before the COM call is made. Similarly, a method call on a COM component typically returns an HRESULT to indicate success or failure. When a COM method call returns an HRESULT that indicates that the call failed, the RCW turns this into an exception (by default), so it can be handled like all other managed code errors.

By allowing managed classes and COM components to interact despite their interface differences, RCWs are an example of the Adapter pattern. The Adapter pattern lets you adapt one interface to another. COM doesn't understand the System.String class, so the RCW adapts it to something that it can understand. Even though you can't change how a legacy component works, you can still interact with it. Adapters are frequently used like this.

The Adapter class itself wraps an Adaptee, translating all calls from the client into the appropriate format and sequence of calls. Though this sounds similar to the Decorator, there are several key differences. With a Decorator, the interfaces of the objects you're composing are the same, while the entire point of an Adapter is to allow you to change interfaces.Adapters also have a definite sequence to them; the Adaptee must be contained by the Adapter. A Decorator class doesn't need to know whether it is wrapped by 1 or 500 other classes, since the interfaces are all the same. As a result, the use of Decorators can be transparent to the application, while the use of Adapter cannot.


Hope this helps.

Thanks & Regards,
Arun Manglick

Monday, November 15, 2010

Singleton - Creational

1.1          Introduction

There are times, when one needs to have a class, which can be only instantiated once. Singleton Design Pattern addresses to such situation by providing a design for such classes (known as Singleton class).

1.2          Description

There are at least two solutions or scenario for implementing Singleton Class. The first solution says that there should be only one shared object and reference to that object should be available only through static method like GetInstance() while making the constructor private. A number of clients can be awarded the reference to such shared object. The second solution says that the constructor should be public (as it appears in most cases) but once an object has been instantiated, an exception should be thrown for each successive constructor call; thus limiting the class to only one object.

1.3          An Example

First case Singleton can be used in a data repository or data collection where creation of more than one object can be resource wastage. Hence each client is given a reference to a single shared object to operate on. While the second case Singleton can be used in locking mechanisms. Once a client has got the object, no other client can have an object.

1.4          Class Diagram





1.5          Singleton Design pattern in C# and .NET

Approach 1: Lazy Implementation




class Singleton
  {
        private static Singleton _instance = null;
        protected Singleton() { }

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }

            return _instance;
        }
 }



This lazy initialization in the control block means that the Singleton instance is initialized, or created, only on the first call to the Instance() method. For many applications, this approach works just fine. But this method is not thread safe! Imagine two threads simultaneously checking if the instance of the class is null, when it is actually null! Both of these threads will create instance of our singleton class which is not what we want. To solve this, we use the lock keywork in C#.


Approach 2: Lock Approach

Below is the Sample code using lock.




class Singleton
    {
        protected Singleton() { }
        private static Singleton _instance = null;

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                lock (typeof(Singleton))
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }



There is still some problem in the above code. Some optimizing compilers can optimize out or reorder the lazy initialization code and reintroduce the thread safety problem. To solve this .NET framework has volatile keyword. Using the volatile keyword on the member variable declaration tells the compiler to not reorder the code and forgo optimization.




class Singleton
    {
        protected Singleton() { }
        private static volatile Singleton _instance = null;

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                lock (typeof(Singleton))
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }



This code takes care of thread safety and compiler re-ordering issues.

Now this way of creating the singleton class is completely thread safe but what about the Performance Issues? Unfortunately, every time we want an instance of this class, we have to acquire the lock which affects the performance badly if our application is a heavily threaded application.

Lazy Initialization:

The Framework, during the JIT process, will initialize the static property when (and only when) any method uses this static property. If the property is not used, then the instance is not created. More precisely, what happens during JIT is that the class gets constructed and loaded when any static member of the class is used by any caller. In this case the result is the same.

Approach 3: Thread-safe

The Framework internally guarantees thread safety on static type initialization. In other words, in the example above, there is only one instance that would ever be created of the Singleton class.

Adding the sealed class modifier ensures that this class will not be sub-classed.

Below is a sample Singleton Usage:




class SingleTon
    {
        public int i=6;
        public static SingleTon Instance = new SingleTon(); 

     // Note: Here the non-static constructor will take precedence over static constructor.
       // So you can comment the 'Static' constructor, unless you are required to initialize any  
       // static variable before any object is created.

        static SingleTon()
        { }

        private SingleTon()
        {
            i = 7;
        }

        public static SingleTon GetInstance()
        {
            return Instance;
        }
    }


Hope this helps.

Thanks & Regards,
Arun Manglick