1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| interface Shape { void draw(); }
class Rectangle implements Shape {
@Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
class Circle implements Shape {
@Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
interface Color { void fill(); }
class Red implements Color {
@Override public void fill() { System.out.println("Inside Red::fill() method."); } }
class Blue implements Color {
@Override public void fill() { System.out.println("Inside Blue::fill() method."); } }
abstract class AbstractFactory { public abstract Color getColor(String color); public abstract Shape getShape(String shape) ; }
class ShapeFactory extends AbstractFactory {
@Override 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(); } return null; }
@Override public Color getColor(String color) { return null; } }
class ColorFactory extends AbstractFactory {
@Override public Shape getShape(String shapeType){ return null; }
@Override public Color getColor(String color) { if(color == null){ return null; } if(color.equalsIgnoreCase("RED")){ return new Red(); } else if(color.equalsIgnoreCase("BLUE")){ return new Blue(); } return null; } }
class FactoryProducer { public static AbstractFactory getFactory(String choice){ if(choice.equalsIgnoreCase("SHAPE")){ return new ShapeFactory(); } else if(choice.equalsIgnoreCase("COLOR")){ return new ColorFactory(); } return null; } }
public class AbstractFactoryDemo { public static void main(String[] args) { AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE"); Shape shape = shapeFactory.getShape("CIRCLE"); shape.draw(); AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR"); Color color = colorFactory.getColor("RED"); color.fill(); } }
|