Wednesday, August 15, 2012

Factory Method Design pattern

A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.






package com.jsl.core;
interface Instrument{
  public void play();
}

class Guitor implements Instrument{
  @Override
  public void play() {
   System.out.println("TIN TIN TIN TIN TIN TIN ......");
  }
}

class Piano implements Instrument{
  @Override
  public void play() {
   System.out.println("PPPPPPPEEE PEEEE PEEE .....");                  
  }
}

class InstrumentFacoty{
 public Instrument getInstrument(String name){
     Instrument obj=null;
     if(name.equalsIgnoreCase("Guitor"))
      obj=new Guitor();
     else if(name.equalsIgnoreCase("Piano"))
      obj=new Piano();
     return obj;
   }
}

public class FactoryMethod {
  public static void main(String[] args) {
   InstrumentFacoty obj=new InstrumentFacoty();
   Instrument ins=obj.getInstrument("piano");
   ins.play();
  }
}

No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...