(1) 簡單工廠模式
使用簡單工廠模式設計一個可以創建不同幾何形狀(Shape)的繪圖工具類,如可創建圓形(Circle)、方形(Rectangle)和三角形(Triangle) 對象,每個幾何圖形都要有繪製draw()和擦除erase()兩個方法,要求在繪製不支持的幾何圖形時,提示一個UnsupportedShapeException,繪製類圖並編程實現。
//抽象圖形
public interface Shape{
void draw();
void erase();
}
public class Circle implements Shape{
public void draw(){
System.out.println("Circle draw!");
}
public void erase(){
System.out.println("Circle erasing!");
}
}
public class Rectangle implements Shape{
public void draw(){
System.out.println("Rectangle draw!");
}
public void erase(){
System.out.println("Rectangle erasing!");
}
}
public class Triangle implements Shape{
public void draw(){
System.out.println("Triangle draw!");
}
public void erase(){
System.out.println("Triangle erasing!");
}
}
//工廠
import java.lang.*;
public class ShapeFactory{
public static Shape produceShape(String shapeName)
throws UnsupportedShapeException{
if(shapeName.equals("circle")){
return new Circle();
}else if(shapeName.equals("rectangle")){
return new Rectangle();
}else if(shapeName.equals("triangle")){
return new Triangle();
}else{
throw new UnsupportedShapeException();
}
}
}
class UnsupportedShapeException extends Exception{
public String toString(){
return "繪製不支持該幾何圖形!";
}
}
public class ShapeClient{
public static void main(String[] args){
Shape circle = null;
Shape rectangle = null;
Shape triangle = null;
Shape diamond = null;
try{
circle = ShapeFactory.produceShape("circle");
rectangle = ShapeFactory.produceShape("rectangle");
triangle = ShapeFactory.produceShape("triangle");
circle.draw();
circle.erase();
rectangle.draw();
rectangle.erase();
triangle.draw();
triangle.erase();
}catch(UnsupportedShapeException e){
e.printStackTrace();
}
try{
diamond = ShapeFactory.produceShape("diamond");
diamond.draw();
diamond.erase();
}catch(UnsupportedShapeException e){
e.printStackTrace();
}
}
}
運行結果: