建立型模式之簡單工廠模式(繪製圖形)
阿新 • • 發佈:2019-01-26
題目:
1. 使用簡單工廠模式設計一個可以建立不同幾何形狀(Shape)的繪圖工具類,如可建立圓形(Circle)、矩形(Rectangle)、和三角形(Triangle)物件,每個幾何圖形均具有繪製和擦除兩個方法,要求在繪製不支援的幾何圖形時,丟擲一個異常(UnsupportedShapeException),或實現一個簡單計算器,繪製類圖並程式設計實現。
類圖
package cn.factory1; public class Circle implements Shape { public void init() { System.out.println("建立圓形。。。"); } }
package cn.factory1;
public class Rectangle implements Shape {
public void init() {
System.out.println("建立長方形。。。");
}
}
package cn.factory1;
public interface Shape {
public void init();
}
package cn.factory1; public class ShapeFactory { public static Shape initShape(String name) throws Exception { if(name.equalsIgnoreCase("Circle")){ System.out.println("圖形工廠生產圓形!"); return new Circle(); } else if(name.equalsIgnoreCase("Triangle")) { System.out.println("圖形工廠生產三角形!"); return new Triangle(); } else if(name.equalsIgnoreCase("Rectangle")) { System.out.println("圖形工廠生產長方形!"); return new Rectangle(); } else { throw new Exception("對不起,暫不能生產該種圖形!"); } } public static void deleteShape(String name) throws Exception { if(name.equalsIgnoreCase("Circle")){ System.out.println("已銷燬圓形!"); } else if(name.equalsIgnoreCase("Triangle")) { System.out.println("已銷燬三角形!"); } else if(name.equalsIgnoreCase("Rectangle")) { System.out.println("已銷燬長方形!"); } else { throw new Exception("對不起,圖形工廠中沒有該種圖形!"); } } }
package cn.factory1; public class SimpleFac { public static void main(String[] args) { try { Shape shape; shape = ShapeFactory.initShape("Circle"); shape.init(); //shape = ShapeFactory.initShape("Triangle"); //shape.init(); //shape = ShapeFactory.initShape("Rectangle"); //shape.init(); //shape = ShapeFactory.initShape("app"); //shape.init(); } catch(Exception e) { System.out.println(e.getMessage()); } } }
package cn.factory1;
public class Triangle implements Shape {
public void init() {
System.out.println("建立三角形。。。");
}
}
執行效果圖
注意:這個程式是在SimpleFac類中執行