java4all@1986 java. Powered by Blogger.

What is meant By Factory Pattern?

>> Friday, May 27, 2011

FACTORY PATTERN:
                   Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.


Where to use & benefits



Examples

To illustrate such concept, let's use a simple example. To paint a picture, you may need several steps. A shape is an interface. Several implementing classes may be designed in the following way.
interface Shape {
   public void draw();
}
class Line implements Shape {
    Point x, y;
    Line(Point a, Point b) {
       x = a;
       y = b;
    }
    public void draw() {
       //draw a line; 
    }
}
class Square implements Shape {
    Point start;
    int width, height;
    Square(Point s, int w, int h) {
        start = s;
        width = w;
        height = h;
    }
    public void draw() {
       //draw a square;
    }
}
class Circle implements Shape {
    ....
}

class Painting {
   Point x, y;
   int width, height, radius;
   Painting(Point a, Point b, int w, int h, int r) {
       x = a;
       y = b;
       width = w;
       height = h;
       radius = r;
   }
   Shape drawLine() {
       return new Line(x,y);
   }
   Shape drawSquare() {
       return new Square(x, width, height);
   }
   Shape drawCircle() {
       return new Circle(x, radius);
   }
   ....
}

...
Shape pic;
Painting pt;
//initializing pt 
....
if (line) 
   pic = pt.drawLine();
if (square)
   pic = pt.drawSquare();
if (circle)
   pic = pt.drawCircle();

 From the above example, you may see that the Shape pic's type depends on the condition given. The variable pic may be a line or square or a circle.

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP