- import java.util.*;
- import java.lang.*;
- import java.io.*;
- /* Name of the class has to be "Main" only if the class is public. */
- class Ideone
- {
- public static void main (String[] args) throws java.lang.Exception
- {
- ShapeFactory shapeFactory = new ShapeFactory();
- Shape circle = shapeFactory.getShape("Circle");
- Shape square = shapeFactory.getShape("Square");
- Shape rectangle = shapeFactory.getShape("Rectangle");
- circle.draw();
- square.draw();
- rectangle.draw();
- }
- }
- interface Shape
- {
- void draw();
- }
- class Circle implements Shape
- {
- @Override
- public void draw()
- {
- System.out.println("Circle : draw()");
- }
- }
- class Square implements Shape
- {
- @Override
- public void draw()
- {
- System.out.println("Square : draw()");
- }
- }
- class Rectangle implements Shape
- {
- @Override
- public void draw()
- {
- System.out.println("Rectangle : draw()");
- }
- }
- class ShapeFactory
- {
- public Shape getShape(String shape)
- {
- if (shape == null)
- {
- return null;
- }
- switch (shape.toLowerCase())
- {
- case "circle":
- return new Circle();
- case "square":
- return new Square();
- case "rectangle":
- return new Rectangle();
- default:
- return null;
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0809201513644.html
来源: http://www.codesnippet.cn/detail/0809201513644.html