Monday, June 10, 2013

Prototype Pattern

Prototype Pattern
เป็นรูปแบบการเขียนอีกแบบหนึ่งซึ่ง มีประโยชน์ทางด้านการใช้ Object ที่มีจำนวนมาก ๆ โดยที่ว่าเราไม่ต้องไป New Object กันอีกต่อไปเรื่อย ๆ ซึ่งทำให้เปลืองทรัพยากรด้วย เราก็จะต้องมีตัวต้นแบบ และก็ Clone มาเรื่อย ๆ อย่างเช่น Object ของมอนเตอร์ ในเกม เป็นต้นแบบนี้

UML ของ Prototype Pattern

Client - จะสร้าง Object มาแล้วไปถาม Prototype Class ว่าจะคัดลอก
Prototype - กำหนด Interface class สำหรับการสร้าง Object และ Clone
ConcreatePrototype - เป็นรูปร่างหน้าตาของสิ่งที่สร้างขึ้นมาและสามารถ โคลนตัวเองได้

ตัวอย่าง Code
public interface Prototype {
 public abstract Object clone ( );
}

 

public class ConcretePrototype implements Prototype {
 public Object clone() {
  return super.clone();
 }
}

public class Client {

 public static void main( String arg[] ) 
 {
  ConcretePrototype obj1= new ConcretePrototype ();
  ConcretePrototype obj2 = ConcretePrototype)obj1.clone();
 }

}
ลองนำไปใช้ดูนะครับ จะเป็นประโยชน์มากสำหรับคนทำเกม ทำ Visual Effect ต่าง ๆ

No comments:

Post a Comment