Who should be responsible for creating objects when there are special considerations, such as complex creation logic, a desire to separate the creation responsibilities for better cohesion, and so forth?
Create a Pure Fabrication object called a Factory that handles the creation.
Copy public interface Shape {
void draw ();
}
Copy public class Rectangle implements Shape {
@ Override
public void draw () {
System . out . println ( "rectangle draw" );
}
}
Copy public class Square implements Shape {
@ Override
public void draw () {
System . out . println ( "square draw" );
}
}
Copy public class Circle implements Shape {
@ Override
public void draw () {
System . out . println ( "circle draw" );
}
}
Copy public class ShapeFactory {
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() ;
} else if ( shapeType . equalsIgnoreCase ( "SQUARE" )) {
return new Square() ;
}
return null ;
}
}
Copy public class FactoryPatternDemo {
public static void main ( String [] args) {
ShapeFactory shapeFactory = new ShapeFactory() ;
Shape shape1 = shapeFactory . getShape ( "CIRCLE" );
shape1 . draw ();
Shape shape2 = shapeFactory . getShape ( "RECTANGLE" );
shape2 . draw ();
Shape shape3 = shapeFactory . getShape ( "SQUARE" );
shape3 . draw ();
}
}