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