Register now or log in to join your professional community.
The "Abstract factory pattern" instead is a method to build collections of factories. In some design patterns, a factory object has a method for every kind of object it is capable of creating.
It comes under creational pattern as this pattern responsable for object instance creation
you ask a factory method to create an instance of object without see the behind details about creation process -and communicate with the newly created object by a common interface
So you coding against interface not specific class that might be change in the future
Example:-
you have classes for animals as - lion,dog,fish
you do not code against lion or fish class , instead ask animal interface to create object of type lion or dog
Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual "placeholders" for creation steps), and then delegates the creation details to subclasses that are supplied by the client.
Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new operation.
People often use Factory Method as the standard way to create objects; but it isn't necessary if: the class that's instantiated never changes, or instantiation takes place in an operation that subclasses can easily override (such as an initialization operation).
Factory Method is similar to Abstract Factory but without the emphasis on families.
Factory Methods are routinely specified by an architectural framework, and then implemented by the user of the framework.
Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In factory design pattern, the creation logic is hidden for the client when we create an object.
Factory is creational pattern -> creation of objects. They help hide the details of the object instantiation from the code that uses those objects
Creating objects (products) without specifying the exact class of object that will be created
sample:
public class ImageReaderFactory {
public static ImageReader getImageReasder (InputStream is){
int imageType = determineImageType(is);
switch(imageType) {
case ImageReaderFactory.GIF:
return new GifReader(is);
case ImageReaderFactory.JPEG:
return new JpegReader(is); // etc. }
}
}
In Factory pattern, we create object without exposing the creation logic to the client and refer
tonewly created object using a common interface.
Implementation
public interface IAnimal
{
string makeNoise();
}
public class Cat extend IAnimal
{
public string makeNoise()
{
return "mew";
}
}
public class Dog extend IAnimal
{
public string makeNoise()
{
return "Burking";
}
}
public class AnimalFactory
{
public Animal GetAnimalSound(string name)
{
if (name == null)
{
return null;
}
if (name.Equals("Cat"))
{
return new Cat();
}
else if (name.Equals("Dog"))
{
return new Dog();
}
return null;
}
}
public class Test
{
readonly AnimalFactory _factory = new AnimalFactory();
public Test()
{
var animal = _factory.GetAnimalSound("Cat");
animal.Sound();
}
}
Design Pattern - Factory Pattern
Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Implementation
We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.
Step1
Create an interface.
Shape.java
public interface Shape {
void draw();
}
Step2
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step3
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
Step4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of circle
shape3.draw();
}
}
Step5
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
The Factory Method pattern is generally used in the following situations: A class cannot anticipate the type of objects it needs to create beforehand. A class requires its subclasses to specify the objects it creates. You want to localize the logic to instantiate a complex object.
The factory method pattern should not be confused with the more general notion of factories and factory methods. The factory method pattern is the best-known use of factories and factory methods, but not all uses of factory methods are examples of the factory method pattern – only when inheritance is involved (a class implementing an interface, or derived class, implements a factory method) is it an example of the factory method pattern. More basic uses of factories are not examples of the factory method pattern, and may instead be referred to as the factory pattern or a simple factory;
Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of objects which have common interface.
//IVSR:Factory Pattern //Empty vocabulary of Actual object public interface IPeople { string GetName(); } public class Villagers : IPeople { #region IPeople Members public string GetName() { return "Village Guy"; } #endregion } public class CityPeople : IPeople { #region IPeople Members public string GetName() { return "City Guy"; } #endregion } public enum PeopleType { RURAL, URBAN } /// <summary> /// Implementation of Factory - Used to create objects /// </summary> public class Factory { public IPeople GetPeople(PeopleType type) { IPeople people = null; switch (type) { case PeopleType.RURAL : people = new Villagers(); break; case PeopleType.URBAN: people = new CityPeople(); break; default: break; } return people; } }In the above code you can see the creation of one interface called IPeople and implemented two classes from it as Villagers and CityPeople. Based on the type passed into the factory object, we are sending back the original concrete object as the Interface IPeople.
A Factory method is just an addition to Factory class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass to decide which class to be instantiated.
//IVSR:Factory Pattern public interface IProduct { string GetName(); string SetPrice(double price); } public class Phone : IProduct { private double _price; #region Product Members public string GetName() { return "Apple TouchPad"; } public string SetPrice(double price) { this._price = price; return "success"; } #endregion } /* Almost same as Factory, just an additional exposure to do something with the created method */ public abstract class ProductAbstractFactory { protected abstract IProduct DoSomething(); public IProduct GetObject() // Implementation of Factory Method. { return this.DoSomething(); } } public class PhoneConcreteFactory : ProductAbstractFactory { protected override IProduct DoSomething() { IProduct product = new Phone(); //Do something with the object after you get the object. product.SetPrice(20.30); return product; } }You can see we have used GetObject in concreteFactory. As a result, you can easily call DoSomething() from it to get the IProduct. You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.
a factory method defines what functions must be available in the non-abstract or concrete factory. These functions must be able to create objects that are extensions of a specific class. Which exact subclass is created will depend on the value of a parameter passed to the function.
php example
<?php
abstract class AbstractFactoryMethod {
abstract function makePHPBook($param);
}class OReillyFactoryMethod extends AbstractFactoryMethod {
private $context = "OReilly";
function makePHPBook($param) {
$book = NULL;
switch ($param) {
case "us":
$book = new OReillyPHPBook;
break;
case "other":
$book = new SamsPHPBook;
break;
default:
$book = new OReillyPHPBook;
break;
}
return $book;
}
}class SamsFactoryMethod extends AbstractFactoryMethod {
private $context = "Sams";
function makePHPBook($param) {
$book = NULL;
switch ($param) {
case "us":
$book = new SamsPHPBook;
break;
case "other":
$book = new OReillyPHPBook;
break;
case "otherother":
$book = new VisualQuickstartPHPBook;
break;
default:
$book = new SamsPHPBook;
break;
}
return $book;
}
}abstract class AbstractBook {
abstract function getAuthor();
abstract function getTitle();
}abstract class AbstractPHPBook {
private $subject = "PHP";
}class OReillyPHPBook extends AbstractPHPBook {
private $author;private $title;
private static $oddOrEven = 'odd';
function __construct() {
//alternate between2 books
if ('odd' == self::$oddOrEven) {
$this->author = 'Rasmus Lerdorf and Kevin Tatroe';
$this->title = 'Programming PHP';
self::$oddOrEven = 'even';
} else {
$this->author = 'David Sklar and Adam Trachtenberg';
$this->title = 'PHP Cookbook';
self::$oddOrEven = 'odd';
}
}function getAuthor() {return $this->author;}
function getTitle() {return $this->title;}
}class SamsPHPBook extends AbstractPHPBook {
private $author;
private $title;
function __construct() {
//alternate randomly between2 books
mt_srand((double)microtime()*);
$rand_num = mt_rand(0,1);
if (1 > $rand_num) {
$this->author = 'George Schlossnagle';
$this->title = 'Advanced PHP Programming';
} else {
$this->author = 'Christian Wenz';
$this->title = 'PHP Phrasebook';
}
}function getAuthor() {return $this->author;}
function getTitle() {return $this->title;}
}class VisualQuickstartPHPBook extends AbstractPHPBook {
private $author;
private $title;
function __construct() {
$this->author = 'Larry Ullman';
$this->title = 'PHP for the World Wide Web';
}
function getAuthor() {return $this->author;}
function getTitle() {return $this->title;}
}writeln('START TESTING FACTORY METHOD PATTERN');
writeln('');
writeln('testing OReillyFactoryMethod');
$factoryMethodInstance = new OReillyFactoryMethod;
testFactoryMethod($factoryMethodInstance);
writeln('');
writeln('testing SamsFactoryMethod');
$factoryMethodInstance = new SamsFactoryMethod;
testFactoryMethod($factoryMethodInstance);
writeln('');
writeln('END TESTING FACTORY METHOD PATTERN');
writeln('');
function testFactoryMethod($factoryMethodInstance) {
$phpUs = $factoryMethodInstance->makePHPBook("us");
writeln('us php Author: '.$phpUs->getAuthor());
writeln('us php Title: '.$phpUs->getTitle());
$phpUs = $factoryMethodInstance->makePHPBook("other");
writeln('other php Author: '.$phpUs->getAuthor());
writeln('other php Title: '.$phpUs->getTitle());
$phpUs = $factoryMethodInstance->makePHPBook("otherother");
writeln('otherother php Author: '.$phpUs->getAuthor());
writeln('otherother php Title: '.$phpUs->getTitle());
}function writeln($line_in) {
echo $line_in."<br/>";
}
?>