Topic
Factory mode is a common design pattern. Implement a shape factory ShapeFactory
to create different shape classes. Here we assume that there are only triangles, squares and rectangles of three shapes.
Sample Example
ShapeFactory sf = new ShapeFactory();Shape shape = sf.getShape("Square");shape.draw();>> ---->> | |>> | |>> ----shape = sf.getShape("Triangle");shape.draw();>> />> / >> /____shape = sf.getShape("Rectangle");shape.draw();>> ---->> | |>> ----
解题
直接draw方法
/*** Your object would be instantiated and called as such: * shapefactory SF = new Shapefactory (); * Shape shape = sf.get Shape (ShapeType); * Shape.draw (); */InterfaceShape {voiddraw ();}classRectangleImplementsShape {//Write Your code here Public voidDraw () {System.out.println (" ----"); System.out.println ("| |"); System.out.println (" ----"); }}classSquareImplementsShape {//Write Your code here Public voidDraw () {System.out.println (" ----"); System.out.println ("| |"); System.out.println ("| |"); System.out.println (" ----"); } }classTriangleImplementsShape {//Write Your code here Public voidDraw () {System.out.println (" /\\"); System.out.println (" / \\"); System.out.println ("/____\\"); }} Public classShapefactory {/** * @paramShapeType A String *@returnGet object of type Shape*/ PublicShape Getshape (String shapetype) {//Write Your code here if(Shapetype.equals ("Square")){ return NewSquare (); } if(Shapetype.equals ("Rectangle")){ return NewRectangle (); } if(Shapetype.equals ("Triangle")){ return NewTriangle (); } return NULL; }}
Lintcode: Shape Factory