Skip to main content

Design Pattern 3: Factory Pattern

Design Pattern 3: Factory Pattern


The factory design pattern also falls under the Creational design patterns same as the Singleton pattern. But the scope is different. Ins singleton our scope was the object. Here we focus more on the class.
Lets dig deep into this design pattern.

What is Factory Pattern?

In earlier we talked about the Singleton Pattern where a single object is created and is used throughout the life span of the program. This time its quite different.
In Factory pattern what happens is that the user doesn't get to know the actual implementation of the system instead of that all the created objects are referred via an common interface.
When I mentioned hiding the implementation you might get some familiar vibe. Yes the concept of polymorphism might have crossed your mind. Actually for the implementation of the Factory design pattern we are using interfaces.
Other thing is you might wonder what I mentioned by accessing via a common interface. Actually that is because we are not pre-defining the object creating class. What we do is we let the sub classes to decide which suitable classes will be get initiated.
Find it difficult to understand? Lets go to the implementation and try to figure it out.

Implementation of Factory Pattern

There are few simple steps in creating a factory pattern example:
  • Create an interface
  • Create some concrete classes implementing the interface
  • Create class returning concrete objects (The Factory class) - The factory which creates the objects.
  • An Intermediate Class which will decide which class to initiate
As the First Step let's create a interface.


package FactoryPattern;

public interface MyInterface {
 public void shout();
 public void eat();
}


Now that we created the interface lets create some concrete classes


package FactoryPattern;

public class Dog implements MyInterface {
 @Override
 public void shout() {
  System.out.println("Dog Shouts Bark"); 
 }
 @Override
 public void eat() {
  System.out.println("Dog eats Meat"); 
 }
}



package FactoryPattern;

public class Cat implements MyInterface {

 @Override
 public void shout() {
  System.out.println("Cat shouts Meow"); 
 }
 @Override
 public void eat() {
  System.out.println("Cats Eat Fish"); 
 }
}

Okey now  the ground work is done. Now its time to create the Factory Class where the suitable class is initiated 


package FactoryPattern;

public class MyFactoryClass {
//In this method we are returning the suitable concrete class object

 //Creating a method which return an object of type interface (Object class is not Pre-determined)
 public MyInterface getType(String animal){
  if (animal == null) {
   return null; //Initiate nothing
  }else if (animal.equals("cat")) {
   return new Cat();//Initiate cat class
  }else if (animal.equals("dog") {
   return new Dog();//Initiate Dog class
  } 
  return null;
 }
}


As you can see. The If - Else clauses check for an parameter and then initiate the relevant object.
Now the final Step or the is to create a main method. Which will invoke the factory class method and pass the relevant parameter.



package FactoryPattern;

public class MyFactoryInvoker {
 public static void main(String[] args) {
  //here we are making a object of the Factory
  //Still the real implementation is hidden from the user
  MyFactoryClass factory = new MyFactoryClass();
  
  //next we are crating objects of our need
  MyInterface dog1 = factory.getType("dog");
  
  System.out.println("This is "+ dog1.getClass()+" Class");
  dog1.eat();
  dog1.shout();
  
  MyInterface cat1 = factory.getType("cat");
  
  System.out.println("This is "+cat1.getClass()+" class");
  cat1.eat();
  cat1.shout();
 }
}


That's it. Now if you run the program the output will be similar to this:

Throughout the program the basic interface and its concrete classes were hidden from the user. And the program it self will decide at the moment when and which sub class will be initiated.

What are the actual Implementation of Factory Pattern?

Like we discussed in the Singleton pattern lets discuss about the possible usage of the Factory pattern.

  • A kind or authorizing method since the implementation logic is hidden
Other than that its better to use this pattern if you are unsure of the sub classes to be implemented in the future.

That's it with Factory Pattern. See you in the next post.


Popular posts from this blog

Natural Language Processing with Python NLTK part 5 - Chunking and Chinking

Natural Language Processing Using regular expression modifiers we can chunk out the PoS tagged words from the earlier example. The chunking is done with regular expressions defining a chunk rule. The Chinking defines what we need to exclude from the selection. Here are list of modifiers for Python: {1,3} = for digits, u expect 1-3 counts of digits, or "places" + = match 1 or more ? = match 0 or 1 repetitions. * = match 0 or MORE repetitions $ = matches at the end of string ^ = matches start of a string | = matches either/or. Example x|y = will match either x or y [] = range, or "variance" {x} = expect to see this amount of the preceding code. {x,y} = expect to see this x-y amounts of the preceding code source: https://pythonprogramming.net/regular-expressions-regex-tutorial-python-3/ Chunking import nltk from nltk.tokenize import word_tokenize # POS tagging sent = "This will be chunked. This is for Test. World is awesome. Hello world....

Natural Language Processing with Python NLTK part 1 - Tokenizer

Natural Language Processing Starting with the NLP articles first we will try the  tokenizer  in the NLTK package. Tokenizer breaks a paragraph into the relevant sub strings or sentences based on the tokenizer you used. In this I will use the Sent tokenizer, word_tokenizer and TweetTokenizer which has its specific work to do. import nltk from nltk.tokenize import sent_tokenize, word_tokenize, TweetTokenizer para = "Hello there this is the blog about NLP. In this blog I have made some posts. " \ "I can come up with new content." tweet = "#Fun night. :) Feeling crazy #TGIF" # tokenizing the paragraph into sentences and words sent = sent_tokenize(para) word = word_tokenize(para) # printing the output print ( "this paragraph has " + str(len(sent)) + " sentences and " + str(len(word)) + " words" ) # print each sentence k = 1 for i in sent: print ( "sentence ...

Design Patterns 1 : Introduction

Design Patterns : Introduction So its the holiday time and thought of starting with the Design patterns. In this post I'll talk about What are design patterns?, What good to us using them?, Why and when use them? and many more. So why wait? Lets start the journey to Design patterns. What are Design patterns? So over the years when programmers tried to build systems that can solve problems often they encountered problems that were difficult to overcome. So after finding a solution what they did was presenting it as an future guideline where other programmers when encountered the same problem can easily surpass that. These are what we called as Design Patterns. To see how it all started we have to go back in the past. History of Design Patterns? All these patterns buzz started in about 1977/79 when  Christopher Alexander  showed interest in using using pattern in architecture. That's right not in computer, in architectural ...