ตัวอย่างโค้ด ของ แบบแผนแฟกทอรีเมธอด

ภาษาจาวา

ตัวอย่างโปรแกรมคำนวณหาปริมาตรของรูปทรงกระบอกซึ่งมีสูตรดังนี้

ปริมาตร = พื้นที่ฐาน * ความสูง

โดยที่

  • แฟกทอรีเมธอดทำหน้าที่สร้างรูปวงกลม
  • ปริมาตรของทรงกระบอกคือผลคูณของความสูงและพื้นที่ฐานจากรูปวงกลมที่ถูกสร้างโดยแฟกทอรีเมธอด

คลาสนามธรรม Container นิยามแฟกทอรีเมธอด createBase() getHeight() และ getVolume() ซึ่งเป็นเทมเพลตเมธอดมีรายละเอียดการคำนวณหาปริมาตร

public abstract class Container {        /**     * Factory method     */    public abstract TwoDShape createBase();    public abstract double getHeight();        /**     * Template method     */    public double getVolume() {        return createBase().getArea() * getHeight();    }}

คลาสรูปธรรม Cylinder สร้างรูปวงกลม Circle ในแฟกทอรีเมธอด createBase()

public class Cylinder extends Container {        private double radius;    private double height;    public Cylinder(double radius, double height) {        this.radius = radius;        this.height = height;    }    @Override    public TwoDShape createBase() {        return new Circle(radius);    }    @Override    public double getHeight() {        return height;    }}

คลาส TwoDShape และ Circle

public interface TwoDShape {    public double getArea();}public class Circle implements TwoDShape {        private double radius;    public Circle(double radius) {        this.radius = radius;    }    public double getArea() {        return Math.PI * radius * radius;    }}

ใกล้เคียง