/** * 工廠模式是一種創建模式,因爲此模式提供了更好的方法來創建對象。 * 在此模式中,我們創建對象而不將創建邏輯暴露給客戶端。 * 例子-如何使用工廠模式創建對象 * 由工廠模式創建的對象將是形狀對象,如圓形、矩形。 * @author ruis * */ /** * 設計一個接口來表示Shape * @author ruis * */ public interface Shape { //接口方法:畫圖的方法 void draw(); } |
/** * 創建實現接口的具體類 矩形類 * @author ruis * */ public class Rectangle implements Shape {
@Override public void draw() { //包含一個畫矩形的方法 System.out.println("Inside Rectangle::draw()method."); }
}
|
/** * 創建實現接口的具體類的方法 圓形類 * @author ruis * */ public class Circle implements Shape {
@Override public void draw() { // 創建一個畫圓形的方法 System.out.println("Inside Circle::draw() method."); }
}
|
/** * 創建實現接口的具體類 正方形類 * @author ruis * */ public class Square implements Shape {
@Override public void draw() { // 一個畫正方形的方法 System.out.println("Inside Square::draw()method."); }
}
|
/** * 核心工廠模式是一個Factory類。 * 以下代碼顯示瞭如何爲Shape對象創建Factory類。 * ShapeFactory類基於傳遞給getShape()方法的String值創建Shape對象。 * 如果String值爲CIRCLE,它將創建一個Circle對象。 * @author ruis * */ /** * 如果形狀爲null,返回null; * 如果是矩形,創建矩形; * 如果是圓形,創建圓形; * 如果是方形,創建方形。 * @author ruis * */ public class ShapeFactory {
//use getShape method to get object of type shape 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; } }
|
/** * 使用Factory類通過傳遞類型等信息來獲取具體類的對象 * 創建形狀工廠對象,獲得工廠可以創建的形狀。 * .get()方法 * @author ruis * */ public class Main {
public static void main(String[] args){ ShapeFactory shapeFactory = new ShapeFactory(); Shape shape1 = shapeFactory.getShape("CIRCLE"); shape1.draw(); Shape shape2 = shapeFactory.getShape("RECTANGLE"); shape2.draw(); Shape shape3 = shapeFactory.getShape("SQUARE"); shape3.draw(); /* Inside Circle::draw() method. Inside Rectangle::draw()method. Inside Square::draw()method. */ } }
|