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.
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
- Connect parallel class hierarchies.
- A class wants its subclasses to specify the object.
- A class cannot anticipate its subclasses, which must be created.
- A family of objects needs to be separated by using shared interface.
- The code needs to deal with interface, not implemented classes.
- Hide concrete classes from the client.
- Factory methods can be parameterized.
- The returned object may be either abstract or concrete object.
- Providing hooks for subclasses is more flexible than creating objects directly.
- Follow naming conventions to help other developers to recognize the code structure.
- Related patterns include
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