工厂模式
2018-03-06 本文已影响6人
863cda997e42
工厂模式
public interface Shape {
void draw();
}
public class Rectangle implements Shape{
public void draw() {
// TODO Auto-generated method stub
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square implements Shape{
public void draw(){
System.out.println("Inside Square::draw() method.");
}
}
public class Circle implements Shape {
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class ShapeFactory {
@SuppressWarnings("unchecked")
public static <T> T getClass(Class<? extends T> clazz) {
T obj = null;
try {
obj = (T) Class.forName(clazz.getName()).newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}
/*
public class ShapeFactory {
public static Object getClass(Class<?extends Shape> clazz) {
Object obj = null;
try {
obj = Class.forName(clazz.getName()).newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}
*/
/*
public class ShapeFactory {
// 使用 getShape 方法获取形状类型的对象
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;
}
}
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
Rectangle rect = ShapeFactory.getClass(Rectangle.class);
rect.draw();
Shape square = ShapeFactory.getClass(Square.class);
square.draw();
Circle circle = ShapeFactory.getClass(Circle.class);
circle.draw();
/*
* Rectangle rect = (Rectangle) ShapeFactory.getClass(Rectangle.class);
* rect.draw(); Square square = (Square)
* ShapeFactory.getClass(Square.class); square.draw(); Circle circle =
* (Circle) ShapeFactory.getClass(Circle.class); circle.draw();
*/
/*
* ShapeFactory shapeFactory = new ShapeFactory();
*
* //获取 Circle 的对象,并调用它的 draw 方法 Shape shape1 =
* shapeFactory.getShape("CIRCLE");
*
* //调用 Circle 的 draw 方法 shape1.draw();
*
* //获取 Rectangle 的对象,并调用它的 draw 方法 Shape shape2 =
* shapeFactory.getShape("RECTANGLE");
*
* //调用 Rectangle 的 draw 方法 shape2.draw();
*
* //获取 Square 的对象,并调用它的 draw 方法 Shape shape3 =
* shapeFactory.getShape("SQUARE");
*
* //调用 Square 的 draw 方法 shape3.draw();
*/
}
}