วัตถุประสงค์ของการเขียนโปรแกรมด้วยรูปแบบ strategy คือ แยกส่วนที่เป็นวิธีการทำงานออกจากการเรียกใช้งาน รองรับการเปลี่ยนวิธีการทำงานในขณะที่ใช้งาน และสามารถเพิ่มวิธีการทำงานใหม่ๆเข้าไปได้โดยไม่กระทบกับโปรแกรมเดิม
วิธีการคือแยกวิธีการทำงานของกลุ่มงานแบบเดียวกันออกเป็นแต่ละคลาสตามวิธีการทำงานที่แตกต่างกัน เช่น หากเราเขียนโปรแกรมเพื่อเข้ารหัสข้อมูล โดยมีวิธีการเข้ารหัสข้อมูลอยู่มากกว่า 1 แบบให้ผู้ใช้งานเลือกใช้ แทนที่เราจะเขียนโปรแกรมที่มีอัลกอริธึมทุกแบบไว้ในคลาสเดียวกัน เราจะแยกแต่ละอัลกอริธึมออกเป็นแต่ละคลาส จากนั้นกำหนดวิธีการเรียกใช้งานที่เป็นมาตรฐานเดียวกัน เช่น ใช้ชื่อเมธอดและพารามิเตอร์ที่เหมือนๆกัน และสร้างคลาสที่เป็นตัวเรียกใช้งานแยกต่างหากออกมาโดยคลาสนี้จะเป็นส่วนที่ผู้ใช้เรียกใช้งาน
ในทางปฏิบัติเราจะสร้างคลาสแบบอินเตอร์เฟสเพื่อกำหนดมาตรฐานของการเชื่อมต่อสำหรับแต่ละคลาส และคลาสของวิธีการต่างๆจะต้องอิมพลีเมนท์อินเตอร์เฟสนี้ ตัวอย่าง เช่น
interface Encryption { // กำหนดมาตรฐานการเชื่อมต่อ
void doEncrypt(String text, int key);
}
class EncryptionType1 implements Encryption {
String text;
int key;
@Override
public void doEncrypt(String text, int key) {
System.out.println("Encrypt "+text+" with type 1 algorithm using "+key+" as key.");
}
}
class EncryptionType2 implements Encryption {
String text;
int key;
@Override
public void doEncrypt(String text, int key) {
System.out.println("Encrypt "+text+" with type 2 algorithm using "+key+" as key.");
}
}
จากนั้นสร้างคลาสสำหรับการเรียกใช้งานซึ่งจะเป็นคลาสที่ผู้ใช้งานนำไปใช้
class GetEncryption {
private Encryption encryption;
public void setEncryption(Encryption encryption) {
this.encryption = encryption;
}
public void doEncrypt(String text, int key) {
this.encryption.doEncrypt(text,key);
}
}
ในการเรียกใช้งาน ผู้ใช้จะสร้างออบเจกต์ของตัวเรียกใช้งานขึ้น และกำหนดอัลกอริธึมการเข้ารหัสที่ต้องการ จากนั้นจึงเรียกใช้งานการเข้ารหัส ซึ่งออบเจกต์ตัวเรียกใช้งานจะส่งต่อการทำงานไปยังออบเจกต์ที่ดำเนินการจริงๆอีกทีหนึ่ง สังเกตุว่าเราสามารถเปลี่ยนวิธีการเข้ารหัสได้ในขณะที่ใช้งานโปรแกรม
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
GetEncryption getEncryption = new GetEncryption(); // สร้างออบเจกต์ตัวเรียกใช้งาน
boolean loop = true;
while (loop) {
System.out.println("Enter : 1 for type1, 2 for type2, 0 for exit.");
int selected = scanner.nextInt();
scanner.nextLine();
if (selected == 1) {
getEncryption.setEncryption(new EncryptionType1());
//การสร้างออบเจกต์ใหม่ทุกครั้งที่มีการเปลี่ยนวิธีการทำงานแสดงให้เห็นว่าคลาสที่เรียกใช้แยกขาดจากคลาสที่ทำงานจริง
getEncryption.doEncrypt("test text", 999);
} else if (selected == 2) {
getEncryption.setEncryption(new EncryptionType2());
getEncryption.doEncrypt("test text", 111);
} else if (selected == 0) {
loop = false;
}
}
}
}
Enter : 1 for type1, 2 for type2, 0 for exit.
1
Encrypt test text with type 1 algorithm using 999 as key.
Enter : 1 for type1, 2 for type2, 0 for exit.
2
Encrypt test text with type 2 algorithm using 111 as key.
Enter : 1 for type1, 2 for type2, 0 for exit.
0