ข้ามไปที่เนื้อหาหลัก

บทความ

กำลังแสดงโพสต์จาก มีนาคม, 2013

Factory Pattern

Definition "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses." Example public class MazeGame { public MazeGame() { Room room1 = makeRoom(); Room room2 = makeRoom(); room1.connect(room2); this.addRoom(room1); this.addRoom(room2); } protected Room makeRoom() { return new OrdinaryRoom(); } } public class MagicMazeGame extends MazeGame { @Override protected Room makeRoom() { return new MagicRoom(); } } หรือ /* factory and car interfaces */ interface CarFactory { public function makeCar(); } interface Car { public function getType(); } /* concrete implementations of the factory and car */ class SedanFactory implements CarFactory { public function makeCar() { return new Sedan(); } } class Sedan implements Car { public function getType() {

Delegation pattern and Facade pattern ( façade pattern )

Delegate ( เป็น Adapter แบบหนึ่ง ) delegate เขาบอกว่า ส่วนใหญ่จะใช้เป็น middle tier เพื่อลด coupling ระหว่าง presentation tier กับ business logic tier จากตัวอย่าง โลกภายนอก จะเห็น Printer แต่จริงๆ แล้ว Real Printer เป็นคนทำงาน Basic example class RealPrinter { // the "delegate" void print() { System.out.println("something"); } } class Printer { // the "delegator" RealPrinter p = new RealPrinter(); // create the delegate void print() { p.print(); // delegation } } public class Main { // to the outside world it looks like Printer actually prints. public static void main(String[] args) { Printer printer = new Printer(); printer.print(); } } ข้อดีของการใช้ delegate กับ interface คือ flexible and typesafe. - Flexibility    Class C มี methods เพื่อเปลี่ยนเป็น classes A and B - typesafe    การเพิ่ม implements clauses ช่วยทำให้ type safe, เพราะ แต่ละ class ต้อง