Working with Bridge Software Design Pattern

Hello friends,

I am here to go though one of the useful design pattern called Bridge.

Before talking about its implementation let’s begin with defining it.

As per GOF guys, Bridge Pattern is defined as follows.

Decouple an abstraction from its implementation so that the two can vary independently.”

Well! Let’s understand what they mean and where this pattern can fit into.

In a case when there is more than one version of abstract methods and also many ways to implement them then providing brand new concrete classes of each abstract version may end up with lots of classes. Bridge pattern addresssethe same problem by introducing an interface which works as a bridge between abstract and concreate classes.

uml

Below is the UML for Bridge pattern.

Bridge pattern has four key elements as in the following

  • Abstraction – Client facing class. Keeps the reference of an object of type Implementor.
  • RefinedAbstraction – Extends the Abstraction class to have multiple version of abstract methods.
  • Implementor or Bridge – This interface acts as bridge between an abstraction classes and concreate implementation classes.
  • ConcreteImplementor -This class implements the Implementor interface.

How Bridge Pattern works

We will understand this by simple example.

Let’s assume a scenario when you have couple of types of email to send and have several ways to do it and at the same time, you want to give choice to client to choose the specific type of email and way or method to send it.

This is the perfect example where bridge pattern can be fit as it allows variation of source (or abstract methods) and target (concreate implementations).

Let’s begin the illustration by creating bridge or Implementor interface.

  • ///<summary>  
  • /// The Bridge or Implementor interface  
  • ///</summary>  
  • public interface IEmailSender  
  •   
  •     void SendEmail(string subject, string body);  
  • }  

And then the abstract class which defines the business objects and methods as in the following.

  • ///<summary>  
  • /// The Abstraction class  
  • ///</summary>  
  • public abstract class Email
  •     public IEmailSenderMessageSender  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •   
  •     public string Subject {  
  •         get;  
  •         set;  
  •     }  
  •   
  •     public string Body {  
  •         get;  
  •         set;  
  •     }  
  •   
  •     public abstract void Send();  
  •   

As you can see Email class is holding the reference of IEmailSender to be able to call the appropriate concreate Implementor at runtime. 

Now let’s create the RefinedAbstraction classes which are used to support the multiple versions of abstract methods. Here we have two types of abstractions i.e. SystemEmail and UserEmail.

  • ///<summary>  
  • /// The RefinedAbstraction class  
  • ///</summary>  
  • public class SystemEmail: Email  
  •     public override void Send()  
  •     {  
  •         string emailSubject = string.Format(“Subject: {0} from System”, Subject);  
  •         string emailBody = string.Format(“Email Body:\n{0}”, Body);  
  •         MessageSender.SendEmail(emailSubject, emailBody);  
  •   
  •     }  
  •   
  • }  
  •   
  • ///<summary>  
  •   
  • /// The RefinedAbstraction class  
  •   
  • ///</summary>  
  •   
  • public class UserEmail: Email   
  • {  
  •     publicoverridevoid Send()  
  •     { 
  •         stringemailSubject = string.Format(“Subject: {0} from User”, Subject);  
  •   
  •         stringemailBody = string.Format(“Email Body:\n{0}”, Body);  
  •   
  •         MessageSender.SendEmail(emailSubject, emailBody);  
  •     }  
  • }  

And here comes the concrete implementation classes. These classes support the idea of multiple targets.

  • ///<summary>  
  • /// The ConcreteImplementor class  
  • ///</summary>  
  • public class WebServiceEmailSender: IEmailSender  
  • {  
  •     publicvoidSendEmail(string subject, string body)  
  •     {  
  •         Console.WriteLine(“Sending Email using WebService:\n{0}\n{1}\n”, subject, body);  
  •     }  
  • }  
  •   
  • ///<summary> 
  • /// The ConcreteImplementor class  
  • ///</summary>  
  •   
  • public class WCFEmailSender: IEmailSender  
  • {  
  •     public void SendEmail(string subject, string body)  
  •     {  
  •         Console.WriteLine(“Sending Email using WCF:\n{0}\n{1}\n”, subject, body); 
  •     } 
  • }  
  •   
  • ///<summary>  
  •   
  • /// The ConcreteImplementor class  
  •   
  • ///</summary>  
  •   
  • public class WebAPIEmailSender: IEmailSender  
  •     public void SendEmail(string subject, string body) 
  •     { 
  •         Console.WriteLine(“Sending Email using Web API:\n{0}\n{1}\n”, subject, body);  
  •     }   
  • }  

As you can see above that we have given three types of concrete implantations to client to choose from. 

So at this point, we are done with required setups. Now let’s use that in client and see the action.

  • Console.Title = “Bridge pattern demo”;  
  •   
  • IEmailSenderwebService = newWebServiceEmailSender();  
  •   
  • IEmailSenderwcf = newWCFEmailSender();  
  •   
  • IEmailSenderwebApi = newWebAPIEmailSender();  
  •   
  • //System Email  
  •   
  • Emailemail = newSystemEmail();  
  •   
  • email.Subject = “Test Message”;  
  •   
  • email.Body = “Hi there, This is a Test Message from System”;  
  •   
  • email.MessageSender = webService;  
  •   
  • email.Send();  
  •   
  • email.MessageSender = wcf;  
  •   
  • email.Send();  
  •   
  • email.MessageSender = webApi;  
  •   
  • email.Send();  
  •   
  • //User Email  
  •   
  • email = newUserEmail();  
  •   
  • email.Subject = “Test Message”;  
  •   
  • email.Body = “Hi there, This is a Test Message from Prakash”;  
  •   
  • email.MessageSender = webApi;  
  •   
  • email.Send();  

Output

output

You can see by using Bridge pattern how smoothly the client can select the version of abstract methods (between SystemEmail and UserEmail) and concreate implementations (among WebService, WCF and Web API).

Note

Sometimes people get confused with the purpose of Bridge pattern with Adapter. Please note that Adapter pattern is used to make two incompatible interfaces to work which are having similar functionality but their method names or return types are different. On the other side, Bridge pattern is used when client needs a choice to select from a variety of abstract methods and concrete implementations and both abstract methods and concrete implementations can be modified independently.

Hope you have liked the article. I leook forward for your comments/suggestions.

Working with Builder Software Design Pattern

Hello friends,

Hope you are doing great. Today Lets go through another software design pattern called Builder.

Before talking about its implementation let’s begin with defining it.

As per GOF, Builder pattern is defined as following.

“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

Well, let’s understand what they mean. As the name suggests, builder pattern is used to build or construct objects by parts or step-by-step. The complex logic of object construction is separated from client ,and client gets the required object and information just by passing a set of details. For example, to build a car, we first need to build the body, engine, and seats and so on. Builder pattern follows the same approach.
Builder pattern has four sub-components as in the following.

  • Product
  • Builder
  • Concrete Builder
  • Director

Now, let’s see how to implement this pattern by taking the same car example.

Firstly, we need to have few enums to outline the parts as in the following.

  • public enum BodyType  
  • {  
  •     HatchBack,  
  •     Sedan,  
  •     SUV  
  • }  
  •   
  • public enum EngineType  
  • {  
  •     Petrol,  
  •     Diesal,  
  •     Hybrid  
  • }  
  •   
  • public enum SeatType  
  • {  
  •     Regular,  
  •     SemiSleeper,  
  •     Sleeper  
  • }  

So, the parts are ready. Now, let’s build the product; i.e., Car. Car class need to have attributes required to build the car. 

  • class Car  
  • {  
  •     string carName;  
  •     public Car(stringcarName)  
  •     {  
  •         this.carName = carName;  
  •     }  
  •     public string CarName  
  •     {  
  •         get   
  •         {  
  •             return carName;  
  •         }  
  •     }  
  •     public BodyType CarBodyType  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •     public EngineType CarEngineType  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •     public SeatType CarSeatType  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •   
  •     public string GetDetails()   
  •     {  
  •         return string.Format(“Name: {0}\nBodyType: {1}\nEngineType: {2}\nSeatType: {3}”, CarName, CarBodyType, CarEngineType, CarSeatType);  
  •     }  
  • }  

Now we are done with building Product (i.e. car), now let’s create the Builder which should have methods to build various parts of the Product. 

  • interface ICarBuilder  
  • {  
  •     void BuildBody();  
  •     void BuilEngine();  
  •     void BuilSeats();  
  •     Car MyCar  
  •     {  
  •         get;  
  •     }  
  • }  

We have created Builder as well. What next?

Next will be the Concrete Builder, but why?

Well, concrete builder is required to build a variety of cars and to handle customization passed from client. For example, if we want to build Maruti and Skoda cars, we need to have two concrete builders such as MarutiCarBuilder and SkodaCarBuilder as in the following:

  • class MarutiCarBuilder: ICarBuilder   
  • {  
  •     Car car = null;  
  •     public MarutiCarBuilder()  
  •     {  
  •         car = new Car(“Maruti”);  
  •     }  
  •   
  •     public void BuildBody()  
  •     {  
  •         car.CarBodyType = BodyType.HatchBack;  
  •     }  
  •   
  •     public void BuildEngine()  
  •     {  
  •         car.CarEngineType = EngineType.Petrol;  
  •     }  
  •   
  •     public void BuildSeats()  
  •     {  
  •         car.CarSeatType = SeatType.Regular;  
  •     }  
  •   
  •     public CarMyCar   
  •     {  
  •         get  
  •         {  
  •             return car;  
  •         }  
  •     }  
  • }  
  •   
  • class SkodaCarBuilder: ICarBuilder  
  • {  
  •     Car car = null;  
  •     public SkodaCarBuilder()  
  •     {  
  •         car = new Car(“Skoda”);  
  •     }  
  •   
  •     public void BuildBody()   
  •     {  
  •         car.CarBodyType = BodyType.Sedan;  
  •     }  
  •   
  •     public void BuilEngine()   
  •     {  
  •         car.CarEngineType = EngineType.Diesal;  
  •     }  
  •   
  •     public void BuilSeats()   
  •     {  
  •         car.CarSeatType = SeatType.SemiSleeper;  
  •     }  
  •   
  •     public Car MyCar  
  •     {  
  •         get  
  •         {  
  •             return car;  
  •         }  
  •     }  
  • }  

I hope you have realized the beauty and power of Builder pattern that, for any future car, we need to just have one builder created for that car.

So by now we have created three sub-components of Builder pattern i.e. Product, Builder, and Concrete Builder. Let’s create the remaining one, that is Director, which will have a method to build the Product by taking the appropriate builder object.

  • class CarManufacturer  
  • {  
  •     public void BuildCar(ICarBuildercarBuilder)   
  •     {  
  •         carBuilder.BuildBody();  
  •         carBuilder.BuilEngine();  
  •         carBuilder.BuilSeats();  
  •     }  
  • }  

We are done with the setup now. Let’s see how client uses this.

  • static void Main()  
  • {  
  •         Console.Title = “Builder pattern demo”;  
  •         CarManufacturercarMfg = newCarManufacturer();  
  •         ICarBuildercarBuilder = null;  
  •   
  •         ////Build Maruti Car  
  •         carBuilder = newMarutiCarBuilder();  
  •         carMfg.BuildCar(carBuilder);  
  •         Console.WriteLine(“Built Car Specs are:\n\n{0}”, carBuilder.MyCar.GetDetails());  
  •   
  •         ////Build Skoda car  
  •         carBuilder = newSkodaCarBuilder();  
  •         carMfg.BuildCar(carBuilder);  
  •         Console.WriteLine(“Built Car Specs are:\n\n{0}”, carBuilder.MyCar.GetDetails());  
  • }  

Output

Output

I hope you have liked the article. I look forward to your comments/suggestions.

String and StringBuilder in Design and Action

Hello Friends, Lets have a look at old yet relevant point about String and String Builder. Both constructs are meant to manipulate the strings but in their own way.

A string (namespace: System.String ) is a sequential collection of Unicode characters that represent text. A String object is immutable (read-only) and a sequential collection of System.Char objects that represent a string. The maximum size of a String object in memory is 2 GB (about 1 billion characters).

Although a string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. However after boxing, the comparison happens on string instances.

  • string a = “prakash”;  
  • string b = “p”;  
  • b += “rakash”;  // Append to contents of ‘b’  
  • Console.WriteLine(a ==b);  //True  
  • Console.WriteLine((object)a == (object)b); //False as after boxing the //comparison happens on string instance and both are differentstring instance   

On the other hand, a StringBuilder (System.Text.StringBuilder) represents a mutable string of characters. This class cannot be inherited.

The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters.

  • StringBuilder sb = new StringBuilder();  
  • sb.Append(“Prakash”);  
  • sb.Append(“Tripathi”);  
  • Console.WriteLine(sb.ToString());  

How it works

The compiler creates a new string object for each string concatenation to hold the new sequence of characters (in other words the existing string and the new data), and that new object is assigned back to the variable.

For example, if you are concatenating two strings then string concatenation would allocate a new string of length (str1.Length + str2.Length) and copy the first and second strings into place.

This results in many re-copying of strings, for example concatenation of N strings (var result = str1 + str2 + str3 + … + strN;) will require N-1 allocations and N-1 copy operations. This can get very expensive for a large N.

On the other hand, a StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is appended to the new buffer.

For example, if you are concatenating 20 strings then StringBuilder simply appends one after another to its buffer and finally returns the result when requested.When to use what

Do not use a string when you don’t know the number of concatenations or if the number of concatenations are karge. For example it’s not good to use a string in the following example.

  • //Inefficient code! Do not use!  
  • string x = “”;  
  • for (int i = 0; i < 100000; i++)  
  • {  
  •     x += “!”;  
  • }  

Use the String class if you are concatenating a fixed number of String objects. In that case, the compiler may even combine individual concatenation operations into a single operation especially in the case of the concatenation of string literals as below.

  • //Efficient code  
  • stringx = “Hello” + ” ” + “Prakash”;  

On the other hand, do not use StringBuilder for trivial concatenation since allocation and initialization of StringBuilder takes some time that may not be useful for a fewer number of concatenations.

For example, the following is the bad example of StringBuilder.

  • //Inefficient code! Do not use!  
  • StringBuilder sb = new StringBuilder();  
  • sb.Append(“Hello”);  
  • sb.Append(“Prakash”);  
  • Console.WriteLine(sb.ToString());  

Use a StringBuilder object if you are concatenating an arbitrary number of strings; for example, if you’re using a loop to concatenate a random number of strings of user input. Or in the case of a big loop as in the following.

  • //Efficient code  
  • StringBuilderbuilder = new StringBuilder();  
  • for (int i = 0; i < 100000; i++)  
  • {  
  •     builder.Append(“!”);  
  • }  
  • x = builder.ToString();  

Performance Comparison

I have tested the performance comparison of String and StringBuilder in a large loop (100000 iterations) in my machine and the following are the findings.

  • int dt1 = DateTime.Now.Millisecond;  
  • Console.WriteLine();  
  • string x = “”;  
  • for (int i = 0; i < 100000; i++)  
  • {  
  •     x += “!”;  
  • }  
  • int dt2 = DateTime.Now.Millisecond;  
  • Console.WriteLine(“Time taken in string concatenation: {0} MS”, dt2 – dt1);  
  • int dt3 = DateTime.Now.Millisecond;  
  • StringBuilderbuilder = new StringBuilder();  
  • for (int i = 0; i < 100000; i++)  
  • {  
  •    builder.Append(“!”);  
  • }  
  • x = builder.ToString();  
  • int dt4 = DateTime.Now.Millisecond;  
  • Console.WriteLine(“Time taken in StringBuilder concatenation: {0}MS”, dt4 – dt3);  

Output 

StringBuilder in C#

Please note that the difference in time in both can be even more when doubling the iterations. Also the results above could vary based on the machine configuration.

Some Tips 

StringBuilder can be even more efficient when limiting the size to its constructor to avoid doubling its buffer size when it runs out of room.

Also if you have an array of things to concatenate, consider calling “String.Concat” explicitly or “String.Join” if you need a delimiter.

References: MSDN and Stackoverflow