เมนูนำทาง
แบบแผนแฟกทอรีเมธอด ตัวอย่างโค้ดตัวอย่างโปรแกรมคำนวณหาปริมาตรของรูปทรงกระบอกซึ่งมีสูตรดังนี้
ปริมาตร = พื้นที่ฐาน * ความสูง
โดยที่
คลาสนามธรรม 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; }}
เมนูนำทาง
แบบแผนแฟกทอรีเมธอด ตัวอย่างโค้ดใกล้เคียง
แหล่งที่มา
WikiPedia: แบบแผนแฟกทอรีเมธอด http://www.developer.com/java/ent/article.php/6184... http://gsraj.tripod.com/design/creational/factory/... http://www.kmitl.ac.th/~s8010403/FMD.htm https://web.archive.org/web/20060923030216/http://... https://web.archive.org/web/20070824142216/http://...