Look at the following points:
- Okay. We will start with a simple party example.
- Consider the following scenario.
- public void partynighty(string brand)
- {
- if (brand == "MH")
- {
- Alcohol ol = new MH();
- }
- if (brand == "MC")
- {
- Alcohol ol = new MH();
- }
- if (brand == "Bacardi")
- {
- Alcohol ol = new Bacardi();
- }
- ol.drink();
- ol.dance();
- ol.talkthetruth();
- ol.sleepwell();
- }
- I have organized a party for the night. I have invited my friends.
- Now, see; all my friends will like to drink their own favorite brand.
- But everyone, after drinking will do the same, like dancing, talking and so on.
In this scenario the brand of alcohol will vary but the behaviour after drinking is the same across all my friends.
- So if I have this functionally in my main class, I should vary the brand now and then, depending upon my friend's tastes. If my class has a huge amount of functionally then it becomes harder to introduce new brands.
Identifying what varies and what stays the same.
- So let's take out the initailzisation of new brands and put them into another class.
- It's actually simple. See the following:
- public class AlcoholFa
- {
- Alcohol alco;
-
- public Alcohol Getmyjoy(string brand)
- {
- Alcohol ol = null;
- if (brand == "MH")
- {
- ol = new MH();
- }
- if (brand == "MC")
- {
- ol = new MH();
- }
- if (brand == "bakadi")
- {
- ol = new Bacardi();
- }
- return ol;
- }
- }
- public class Alcohol
- {
-
- private Alcohol()
- {
-
- }
- public Alcohol getmydrinks(string brd)
- {
- AlcoholFa fa = new AlcoholFa();
- return fa.Getmyjoy(brd);
- }
- public void drink();
- public void dance();
- public void talkthetruth();
- public void sleepwell();
- }
- public class MH : Alcohol
- {
-
- }
- public class MC : Alcohol
- {
-
- }
- public class Bacardi : Alcohol
- { }
- Now our main class is very simplified. It looks as in the following:
- Alcohol ol;
-
- ol = getmine("MC");
- ol.drink();
- ol.dance();
- ol.talkthetruth();
- ol.sleepwell();
- That's it, we have done our job. Wait a second.
- Suppose we have multiple qualities of each brand, like “A Quality”, “B Quality”, “C Quality”.
- So what to do? Think; take your time.
- Here comes the Factory partner like a superhero. He said that we can create multiple factories and we even allow Clint to choose his own choice and then order his brand.
- So now I can add as many brands as I need dynamically. Note dynamically is important.
- I can even include a new set quality.
- Now everything in my class is dynamic so that I (the “server”; the main class) can easily order any brand in the future without modifying the mail class.
Source Code