Wednesday, May 25, 2016

Creational Design Patterns tutorial example - Factory Method - Java vs Kotlin

This design pattern is all about the class instantiation. These design patterns tries to create objects  in a manner suitable to the situation.
Again there are two sub-categories into it
1) Object-Creational Design Pattern
2)Class-Creational Design Pattern

Object-Creational DP                                                                            Class-Creational DP
1) Abstract Factory DP                                                                         1)Factory Method DP
2)Builder DP
3)Prototype DP
4)Singleton DP

Factory Method Design Pattern:

It is used to instantiate an object from one among a set of classes based on some logic. It is also used instead of constructor or in addition to existing constructor.

eg .sample program for it

public interface Pet{ public String petSound();}
public class Dog implements Pet{  public String petSound(){return "Bow Bow" } }
public class Cat implements Pet{  public String petSound(){return "Meaw Meaw" } }
public class PetFactory{ public Pet getPet(String petType){ if("Bow Bow".equals(petType)){pet=new Dog(); else if("Meaw Meaw.equals(petType){ pet=new Cat();}") }  return pet}}

publi class SampleFactoryMethodTest
  public static void main(String args[])
  {
   PetFactory factory=new PetFattory();
   Pet pet=factory.getPet("Bow");
   System.out.println(pet.petSound());
  }
}
When to use Factory Method Design Pattern
1) when a class cant guess the type of the object it is supposed to create.
2)When a class wants its subclass to be the ones to specific the type of a newly created object.
3)when we want to localize the knowledge of which class gets created.

Example in kotlin : 

fun main() {
val queen = createPiece("qa5")
println(queen)
}

interface ChessPiece {
val file: Char
val rank: Char
}

data class Pawn(
override val file: Char,
override val rank: Char
) : ChessPiece


data class Queen(
override val file: Char,
override val rank: Char
) : ChessPiece

fun createPiece(notation: String): ChessPiece {
val (type, file, rank) = notation.toCharArray()
return when (type) {
'q' -> Queen(file, rank)
'p' -> Pawn(file, rank)
else -> throw RuntimeException("Unknown piece: $type")
}
}

Output : Queen(file=a, rank=5)



No comments: