Working with Prototype Design Pattern

Hello friends, I am resuming series on design patterns. Today we will go through another design pattern called Prototype. It falls under a creational pattern category. Before talking about its implementation let’s begin with defining it.

A prototype is a design pattern that believes and enforces object cloning or copying over new object creation.

But object copy is that important

The answer is simple, copying objects improves performance in a situation when one needs a lot of objects and creating them turns out to be a costly affair.
Since we are talking about copy let’s discuss shallow and deep copy as well.

Shallow Copy

As the name suggests, it’s a partial or incomplete copy and any reference types of the source object will not be copied and will keep on referring to the same memory location.

In .NET it is achieved by the MemberwiseClone method.

Deep Copy

Similar to the name, it’s a real copy of all the members in the source object including reference types. For reference types, it creates a new memory location in heap to provide true copy experience. We need to write custom code to achieve deep copy. Now let’s talk about the implementation of the pattern.
Assume we have an abstract class Vehicle that has the following structure.

  • internal abstract class Vehicle  
  • {  
  •     internal string VehicleType  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •     internal string Brand  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •     internal string Model  
  •     {  
  •         get;  
  •         set;  
  •     }  
  •     internal abstract void ShowDetails();  
  •     internal abstract Vehicle ShallowCopy();  
  •     internal abstract Vehicle DeepCopy();  
  •     internal ExtraInformation MoreInfo = new ExtraInformation();  
  • }  

We can take interface as well but in that we need to override all the properties again which looks duplicate in this case. Here class Vehicle works like the prototype. We have added class ExtraInformation to depict deep copy and shallow copy concepts.

  • class ExtraInformation  
  • {   
  •    internal string Cost { getset; }  
  •    internal int Ratings { getset; }  
  • }  

Now let’s have concrete prototype FourWheelar as in the following.

  • internal class FourWheelar: Vehicle, ICloneable  
  • {  
  •     internal override Vehicle ShallowCopy()  
  •     {  
  •         return this.MemberwiseClone() as Vehicle;  
  •     }  
  •     internal override Vehicle DeepCopy()  
  •     {  
  •         Vehicle vehicle = this.MemberwiseClone() as Vehicle;  
  •         vehicle.MoreInfo = new ExtraInformation();  
  •         vehicle.MoreInfo.Cost = this.MoreInfo.Cost;  
  •         vehicle.MoreInfo.Ratings = this.MoreInfo.Ratings;  
  •         return vehicle;  
  •     }  
  •     internal override void ShowDetails()  
  •     {  
  •         Console.WriteLine(string.Format(“Vehicle Type: {0} \tBrand: {1} \tModel: {2} \tCost: {3} \tRatings: {4}”, this.VehicleType, this.Brand, this.Model, this.MoreInfo.Cost, this.MoreInfo.Ratings));  
  •     }  
  •     public object Clone()  
  •     {  
  •         return DeepCopy();  
  •     }  
  • }  

You can see here that we have also implemented the ICloneable interface. To be frank, it’s not required here but I have added it to present its existence. It just has a Clone method and when called, we are returning the custom DeepCopy method.

So the setup is done now, let’s use this in the client.

  • static void Main()  
  • {  
  •     Console.Title = “Prototype pattern demo”;  
  •     FourWheelar car = new FourWheelar();  
  •     car.VehicleType = “Car”;  
  •     car.Brand = “Maruti”;  
  •     car.Model = “Swift”;  
  •     car.MoreInfo.Cost = “6.5 Lakhs INR”;  
  •     car.MoreInfo.Ratings = 2;  
  •     FourWheelar truck = car.ShallowCopy() as FourWheelar;  
  •     truck.VehicleType = “Truck”;  
  •     truck.Brand = “Tata”;  
  •     truck.Model = “ACE”;  
  •     truck.MoreInfo.Cost = “4.5 Lakhs INR”;  
  •     truck.MoreInfo.Ratings = 3;  
  •     Console.WriteLine(“******************************Shallow Copy******************************”);  
  •     Console.WriteLine(“Origional Object:”);  
  •     car.ShowDetails();  
  •     Console.WriteLine();  
  •     Console.WriteLine(“Shallow Cloned Object:”);  
  •     truck.ShowDetails();  
  • }  

Output:

run

You can see here that when we change the cost and ratings in the target object, the original object is also getting changed. This is happening because the copied object is still holding the same reference as the source.

Now let’s test deep copy.

  • static void Main()  
  • {  
  •     Console.Title = “Prototype pattern demo”;  
  •     FourWheelar car = new FourWheelar();  
  •     car.VehicleType = “Car”;  
  •     car.Brand = “Maruti”;  
  •     car.Model = “Swift”;  
  •     car.MoreInfo.Cost = “6.5 Lakhs INR”;  
  •     car.MoreInfo.Ratings = 2;  
  •     FourWheelar truckNew = car.Clone() as FourWheelar;  
  •     truckNew.VehicleType = “Truck”;  
  •     truckNew.Brand = “Tata”;  
  •     truckNew.Model = “ACE”;  
  •     truckNew.MoreInfo.Cost = “4.5 Lakhs INR”;  
  •     truckNew.MoreInfo.Ratings = 3;  
  •     Console.WriteLine(“******************************Deep Copy******************************”);  
  •     Console.WriteLine(“Origional Object:”);  
  •     car.ShowDetails();  
  •     Console.WriteLine();  
  •     Console.WriteLine(“Deep Cloned Object:”);  
  •     truckNew.ShowDetails();  
  • }  

Output:

Output

As you can see here that when we change the cost and ratings in the target object, original object is not getting changed. This is happening because the copied object is having new reference.

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

Working with Facade Software Design Pattern

Hello friends,

Hope you are doing well. Today we will be looking into another software design pattern called Facade.

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

As per GOF guys, Facade pattern is defined as:

Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

All right! Let’s understand what they mean.

It means that when you have several sub-systems or classes, it’s often difficult for a client to interact with all of them, and if somehow the client manages to interact, the code becomes messy and difficult to maintain for any future change.

How Façade pattern works

Facade addresses the same problem by having just one interface (or wrapper class) to interact with client for all of its need. The wrapper class, internally handles all the complexity of interactions with other sub-systems.

Let’s understand this by a simple example.

We will take the same car example to illustrate the concept.

Let’s begin with building the sub-systems classes as in the following:

  • class Body   
  • {  
  •     public void AssembleBody()  
  •     {  
  •         Console.WriteLine(“Assembling Body…”);  
  •     }  
  • }  
  •   
  • class Engine  
  • {  
  •     public void AssembleEngine()  
  •     {  
  •         Console.WriteLine(“Assembling Engine…”);  
  •     }  
  • }  
  •   
  • class Tyre  
  • {  
  •     public void AssembleTyre()  
  •     {  
  •         Console.WriteLine(“Assembling Tyre…”);  
  •     }  
  • }  
  •   
  • class Accessories  
  • {  
  •     public void AssembleSeat()  
  •     {  
  •         Console.WriteLine(“Assembling Seat…”);  
  •     }  
  •   
  •     public void AssembleMusicSystem()  
  •     {  
  •         Console.WriteLine(“Assembling Music System…”);  
  •     }  
  • }  

So, the sub-system is built now. Now, let’s design our Facade class which will talk to the client by some public methods exposed by it.

  • class CarFacade  
  • {  
  •     Body body;  
  •     Engine engine;  
  •     Tyre tyre;  
  •     Accessories accessories;  
  •   
  •     public CarFacade()  
  •     {  
  •         body = new Body();  
  •         engine = new Engine();  
  •         tyre = new Tyre();  
  •         accessories = new Accessories();  
  •     }  
  •   
  •     public void AssembleCar()  
  •     {  
  •         Console.WriteLine(“Car Assembling Started…”);  
  •         body.AssembleBody();  
  •         engine.AssembleEngine();  
  •         tyre.AssembleTyre();  
  •         accessories.AssembleSeat();  
  •         accessories.AssembleMusicSystem();  
  •         Console.WriteLine(“Car Assembling Done…”);  
  •     }  
  • }  

In the CarFacade class, you can see that we have exposed a public method called AssembleCar to which client will have access. Internally AssembleCar is handling complexity of interactions with sub-systems like Body, Engine, etc.

Now all the required setup is ready, let’s see how client uses this.

  • static void Main()  
  • {  
  •     Console.Title = “Facade pattern demo”;  
  •     CarFacade carFacade = new CarFacade();  
  •     carFacade.AssembleCar();  
  • }  

Output

So as you can see that client only knows about a façade method called AssembleCar and is successfully able to assemble the car without going into the complexity of various sub-systems involved.

Class Diagram

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

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.