Prototype Design Pattern

Prototype design pattern is one of the simplest design pattern. I think of all the design patterns, Prototype is simpler to implement and understand just like Singleton. Lets continue with the Prototype pattern in this post which extends the earlier Design Patterns Series.

Problem Statement

Assume there is a supermarket chain who have their business setup in different parts of a country. When a new store opens up they setup the infrastructure for the store. There are some predefined types of stores like the convenient stores which we can call Express stores. Then there are bigger stores which we can call Super stores. There can be multiple attributes associated with the stores. Each store can have one or more floors for customers to shop. Each store should have at least one checkout counter. The store can be open for customers all throughout the day.  We can keep on adding many more attributes like this. But for simplicity we will stop here. Lets see how we can create these types of stores.

Solution Without Prototype Pattern

Lets start by creating a class which can be used to create these different types of stores.We call this class StoreCreator. The implementation of the class is very straightforward.

    public class StoreCreator

    {

        public Store CreateExpressStore()

        {

            return new Store

                {

                    NumberOfFloors = 1,

                    NumberOfCheckoutCounters = 1,

                    OpenAllDay = false

                };

        }

 

        public Store CreateSuperStore()

        {

            return new Store

                {

                    NumberOfFloors = 2,

                    NumberOfCheckoutCounters = 10,

                    OpenAllDay = true

                };

        }

    }

Based on the above code snippets, we can create two distinct types of stores. An express store which has 1 floor, 1 checkout and is not open for the whole day. Similarly we can create a super store with 2 floors, 10 checkouts and is open for the complete day. The store class is a simple class with just properties.

Now lets look at the client code which uses this class.

    internal class StoreCreatorWithoutPrototype

    {

        public StoreCreatorWithoutPrototype()

        {

            StoreCreator storeCreator = new StoreCreator();

 

            Store bangaloreExpressStore = storeCreator.CreateExpressStore();

            bangaloreExpressStore.Address = "Bangalore";

 

            Store mumbaiExpressStore = storeCreator.CreateExpressStore();

            mumbaiExpressStore.Address = "Mumbai";

 

            Store bangaloreSuperStore = storeCreator.CreateSuperStore();

            bangaloreSuperStore.Address = "Bangalore";

 

            Store delhiSuperStore = storeCreator.CreateSuperStore();

            delhiSuperStore.Address = "Delhi";

            delhiSuperStore.NumberOfCheckoutCounters = 8;

            delhiSuperStore.OpenAllDay = false;

            delhiSuperStore.NumberOfFloors = 4;

 

            Store chennaiSuperStore = storeCreator.CreateSuperStore();

            chennaiSuperStore.Address = "Chennai";

            chennaiSuperStore.NumberOfCheckoutCounters = 8;

            chennaiSuperStore.OpenAllDay = false;

            chennaiSuperStore.NumberOfFloors = 4;

        }

    }

We have created 5 different stores using the above code. First one is the bangaloreExpressStore. Second is the mumbaiExpressStore. Third is the bangaloreSuperStore. For all these three stores we are using the default settings from the respective create methods.

In real life we will always have exceptions or customizations to make. So the next case is a delhiSuperStore which has 8 checkout counters instead of 10. It is not open all day. And it has 4 floors instead of 2.

Next is the chennaiSuperStore which has exactly the same attributes as the delhi super store created previously. We have duplicated most of the code above. Duplicate code is very bad code smell which we should try to avoid at any cost.

Problem with this approach

Apart form the code duplication, the above code can cause other problems. In this case we have only three or four properties, imagine what will happen if we have more than 10-15 properties. Assume only 2-3 properties are same as the default ones and the remaining ones are customized. Lets assume in the above example the delhiSuperStore had customized 12 properties out of 15. Now we need to create the chennaiSuperStore which is exactly same as delhiSuperStore except for the address.

This is a quite common scenario. We have certain object which is initialized with the values. During the course of the execution of the program, we need another object with most of the values same as the already existing object. The cost of creating the object and initializing it can be very high in some scenarios. In our case we are setting the values in create method. Imagine the scenario where a complex object is constructed using different components or services. In this case the cost of constructing another object with similar attributes can be avoided if we have some mechanism of using the already constructed objects values.

This is the objective of the Prototype pattern. It allows us to create a new object by using a fully initialized object which is called the prototype. This is similar to having a model flat when you go to buy a flat in an apartment under construction. Model flat will have most of the common attributes and then build or the developer might give you a choice to customize few things here a and there as per your needs.

Refactored Solution With Prototype Pattern

Lets see how we can refactor our code to fit this criteria. If we look at the classes that we have in our solution, the Store class is the one which we are initializing. Once we have an instance of store class we can make use of it to clone it into another instance. Being the good students of Object Oriented design, we can define an interface which can help us do the cloning part. Since we are going to clone or prototype a store, we can name our interface as IStorePrototype

    public interface IStorePrototype

    {

        Store Clone();

    }

It has only one method Clone which return an instance of Store. Lets look at the class which implements this interface. Any guesses?

    public class Store : IStorePrototype

    {

        public bool OpenAllDay { get; set; }

 

        public string Address { get; set; }

 

        public int NumberOfCheckoutCounters { get; set; }

 

        public int NumberOfFloors { get; set; }

 

        public Store Clone()

        {

            return new Store

                {

                    NumberOfCheckoutCounters = this.NumberOfCheckoutCounters,

                    NumberOfFloors = this.NumberOfFloors,

                    OpenAllDay = this.OpenAllDay

                };

        }

    }

The Store class implements the IStorePrototype interface. The Clone method copies the values for existing properties into the new instance. Lets see the changes on the client who uses this refactored code.

    internal class StoreCreatorWithPrototype

    {

        public StoreCreatorWithPrototype()

        {

            StoreCreator storeCreator = new StoreCreator();

 

            Store bangaloreExpressStore = storeCreator.CreateExpressStore();

            bangaloreExpressStore.Address = "Bangalore";

 

            Store mumbaiExpressStore = storeCreator.CreateExpressStore();

            mumbaiExpressStore.Address = "Mumbai";

 

            Store bangaloreSuperStore = storeCreator.CreateSuperStore();

            bangaloreSuperStore.Address = "Bangalore";

 

            Store delhiSuperStore = storeCreator.CreateSuperStore();

            delhiSuperStore.Address = "Delhi";

            delhiSuperStore.NumberOfCheckoutCounters = 8;

            delhiSuperStore.OpenAllDay = false;

            delhiSuperStore.NumberOfFloors = 4;

 

            Store chennaiSuperStore = delhiSuperStore.Clone();

            chennaiSuperStore.Address = "Chennai";

        }

    }

There is no change in the way we create the first 4 store instances. But look at the last one. Since the chennaiSuperStore needs to have exact same attributes as delhiSuperStore, we just Clone the delhiSuperStore and assign it to chennaiSuperStore. By doing this we get the exact state of the delhiSuperStore at runtime into the chennaiSuperStore instance.

Assume that the retail chain is planning a big expansion and wants to replicate the model to various stores. Using this method mentioned in this post, we can create one or more prototypes or model stores and then easily expand them into the required number of instances.

Conclusion

Prototype pattern is very useful when we want to replicate the state of an initialized object into another instance of the same class. Prototype is a creational pattern and deals with creating instances of a class. People might argue that the same thing can be achieved using a Factory method which takes multiple parameters to create a new instance.

Once again while applying a design pattern, we need to look at its intent and the application of the pattern. The intent of Factory is to create one of the several types of objects of a family of classes. Whereas Prototype pattern is used to initialize a object based on another object which is fully initialized. This is helpful when the creation of an object might be complex compared to cloning it from an existing object.

Lets say the supermarket chain has operations in different countries. We can have a prototype for each county and all the stores within that country can have attributes defined for the country prototype store. This can help easily extend the supermarket chain’s business when it decides to add another country to its operations. It would be as simple as creating a new prototype for the specific country and they can start rolling the stores.

As always the complete working solution is available for download Prototype Design Pattern Demo.zip.

Until next time Happy Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this post.

spacer

9th Anniversary of joining IT industry

2nd June 2003 was an eventful day in my life. It was on this day exactly 9 years ago that I stepped into the IT industry. I can never forget this day in my life. In one way it was and still remains one of landmark days in my life. Although I was offered the job at what was that time called the NetGalactic Internet Solutions Pvt Ltd on 25th May, I had one weeks time to join as we were around 9 or 12 freshers selected as trainees. This is an account of my 9 years journey in IT industry.

How it started

Year 2003 was one of the difficult year to get jobs especially for fresher. The DotCom boom of the late 90’s had sort of dried out and if I remember correctly there was a minor recession period going on during 2003. While I was looking out for opportunities in Bangalore, one of my friend informed me that there is a company in Kormangala which is hiring DotNet developers. I managed to get through the technical rounds and was offered a trainee position. After a week or two weeks of training I started working in the night shift between 8 PM to 6 AM. Being the first job, the work was exciting. I was lucky to work on a Tablet PC based application back in those days. But working during nights was really difficult. After 6 months of night shifts I was lucky to have regular shifts. It was a huge relief. More than anything else it allowed me to have fun and enjoy weekends with my fun loving room mates. Those were the golden days at the beginning of the career.

How it progressed

After working with Netgalactic (now Skelta) for about 18 months I moved to a different company. The move didn’t really work for me and the stay was very short lived there for just about 4 months. During the short duration of 18 months with Netgalactic, I had opportunity to work with some of the best people in Netgalactic. I am sure whoever worked on the Tablet PC app during that time reaped rich dividends in their career.  Such was the learning associated with that project that each and every individual benefited from it in one way or the other.

Thomson Financials (now Thomson Reuters) was my next break. This was one of the biggestThomson breaks of my career. I worked with Thomson for close to three years. I had so many opportunities to attend world class trainings and I owe many of my current skills to the knowledge that I gained during that time. Till date this has been my best company in terms of work life balance and overall work culture. The group where I worked was and in fact still is like a well knit family. You automatically get embraced in their culture. Within one or two weeks of joining you feel like an integral part of the family.

I am not at all surprised that the attrition rate is the lowest among all my friends and colleagues who were working with me back in 2005. I very rarely have to update their mail ids. I miss the work culture of Thomson very badly.

UKMy next stopover was with one of the worlds largest retailer and definitely UK’s number one Tesco. It was at Tesco that my career graph really started moving upwards. I had opportunity to work with my colleagues in UK for short duration. The visit to UK was helpful in understanding various things. The best thing I learnt at Tesco was the system design and Architecture. I had the opportunity to work with some of the best people in Tesco. My knowledge and experience of Agile started with Tesco. I appreciated the Tesco values  very much. If I miss anything after leaving Tesco then it certainly has to be the values and the culture. The experience I had during my three years of career with Tesco is something very very special. I still have many contacts in Tesco HSC and Tesco UK with whom I interact on regular basis. I miss working with these wonderful people.

Korea International Team membersThe quality of work that I was involved in during my role as Tech Lead of the Instore team was something that I cherish the most. The guys who worked on the Korea International project with me were a great team. I miss them very very much. The whole Instore team inspired me to give my Technical best and I am craving for work of similar complexity ever since leaving Tesco. For those people who worked with me during my Tesco days, they know how much I loved to talk about the Picking Algorithm. Even after 18 months of leaving Tesco, I still remember most of the complex pieces that I had worked on, related to the Picking Algorithm.

Korea International III hope some day in future I’ll find work which is equally challenging and interesting enough to say that I worked on a project better than the Picking Algorithm. Until then for me Picking Algorithm or Picking Control System (PCS) as it is known in Tesco is the best project I have ever worked on.

 

 

 

Current situation

ParisLast but not the least, currently I am working as a consultant for a French Investment Bank in Singapore for past 18 months. The switch from India to Singapore has been good so far. I definitely added more firepower to my arsenal of technical skills here. But somehow I feel Tesco was the pinnacle of my technical journey. Life is much smooth in Singapore compared to India but somehow I feel the technical challenges in India were more compared to the current state in Singapore. Obliviously I can’t expect same kind of work in all the places. The beauty of IT industry is that it gives us the opportunity to experiment a bit.

Future

Two years back I had never thought I’ll be in Singapore. Similarly I don’t know what next 24 months have in store for me. Given the dynamic nature of IT industry I don’t really like to plan beyond a period of 6 months or so. Hopefully things will continue to be good and I can hope for better. In my career so far I am yet to complete 3 years in a single organization. Both Thomson as well as Tesco I came very close but missed out by one or two weeks. I hope I’ll be able to stay long enough in my current job to beat that.

Looking Back

When I look back at my journey from a trainee programmer to a Tech Lead, it gives me a great satisfaction. I am fortunate enough to have worked with some of the best people in the industry. I had opportunity to interact with people from all over the globe. I was fortunate enough to travel to different countries in UK, Europe and Asia because of my job. I don’t think I would have enjoyed so much in any other industry other than the IT. If it was not for IT, I would not have been able to afford all the gadgets including smartphones and notebook PCs to say the least. I feel proud to be associated with this wonderful industry. Nine years is too short a period to gauge some ones career. But certainly it is far better than many other industries where life becomes stagnant after couple of years. Best thing I like about IT industry is the everyday challenges and never ending scope for innovation.

A bit of advise for anyone looking to build your career in IT

It is very easy to get distracted by the advise of others. I certainly found it difficult during my job search as people kept telling it will be difficult to find a job in IT. For any youngster trying to make it big in IT industry here is a piece of advice based on my personal experience. IT industry is one of the most open industry you’ll ever find in the world. You get rewarded in direct proportion to the efforts you put in. If you are willing to learn and adapt you’ll always have enough work in IT. All you need is the will and the skill to get the job done. Look at all the success stories in IT, not everyone is holding a high profile degree from some renowned university or something like that. More often than not, most of the success stories are related to the people who though out of the box and brought out the innovation. You don’t need to go too far back in history, Bill Gates and Steve Jobs are classic examples.

Don’t get complacent in your job. Always remember that to survive in IT, you need to keep sharpening the axe. Don’t be single dimensional. Try to add more than one skill to your skill set. Initially during the first couple of years it might be difficult to choose what kind of work you would like to be involved with. But after that as you move into the  4th or 5th year of your career you need to make a choice whether you want to continue with what you are doing or you wish to move into different roles like management.

Like in any other industry, IT industry is also full of extremes. You’ll find extraordinary things on one side as well as what people like to call bull shit or crap to be very modest on the other. It all depends on which side you want to be with. If you treat your profession as a craft and yourself as a craftsman you will surely end us on the good side. Even a stopped watch is correct twice a day. If unfortunately you end up in a wrong place, I would suggest try to find the positives in those situations as well. Make an attempt to make things better than you found them previously. If you love your craft you’ll never feel bored of your work.

Conclusion

I have thoroughly enjoyed my journey of 9 years in IT industry. I can’t think of any other alternative career where I would have enjoyed so much. May be I was lucky enough to be in the right place at the right time. Over these 9 years I always loved my work and I hope it will continue to be the same forever. I take this opportunity to thank each and every individual who helped me during my progression in all these years, my family, friends, colleagues, mentors and people from the developer community. Without your support I would not have been what I am today. The journey has been far more rewarding and exceeding the expectations. I wish the coming years will be even more encouraging and rewarding for all of us involved in this industry.

Signing off as a proud and passionate IT Engineer.

spacer