วัตถุประสงค์ของการเขียนโปรแกรมแบบ facade คือลดความซับซ้อนในการเรียกใช้งานระบบงานในกรณีที่ระบบงานประกอบไปด้วยหลายๆส่วนประกอบเพื่อให้ง่ายสำหรับผู้ใช้งาน โดยแทนที่ผู้ใช้งานจะต้องเรียกใช้หลายๆส่วนประกอบเองเพื่อเริ่มการทำงานที่ต้องการ เราจะสร้างส่วนติดต่อกับผู้ใช้ที่จะดำเนินงานต่างเหล่านั้นให้โดยที่ผู้ใช้งานจะไม่ทราบถึงความซับซ้อนที่เกิดขึ้น นอกจากนี้เราสามารถใช้รูปแบบนี้ในการจัดกลุ่มของระบบงานย่อยให้เป็นหมวดหมู่เพื่อให้ง่ายต่อการใช้งานด้วยคำสั่งที่น้อยลงและทำให้แต่ละกลุ่มงานเป็นอิสระต่อกัน
วิธีการคือเราสร้างคลาสที่ประกอบด้วยเมธอดที่จะไปเรียกส่วนประกอบต่างๆที่ต้องการมาทำงานโดยที่ผู้ใช้งานเพียงเรียกใช้เมธอดดังกล่าวเท่านั้น
ตัวอย่าง เช่น เมื่อเราต้องการใช้งานรถยนต์ เราจะต้องสตร์าทเครื่องยนต์ เปิดแอร์ เปิดวิทยุ เป็นต้น ซึ่งขั้นตอนต่างๆนี่สามารถจำลองเป็นโปรแกรมได้ดังนี้
class Engine {
String engine;
public Engine(String t) {
this.engine = t;
}
void start() {
System.out.println("Start engine");
}
void stop() {
System.out.println("Stop engine");
}
}
class AirCon {
String aircon;
public AirCon(String t) {
this.aircon = t;
}
void turnOn() {
System.out.println("Turn on air conditioner");
}
void turnOff() {
System.out.println("Turn off air conditioner");
}
}
class Radio {
String radio;
public Radio(String t) {
this.radio = t;
}
void turnOn() {
System.out.println("Turn on radio");
}
void turnOff() {
System.out.println("Turn off radio");
}
}
เราสามารถทำให้การเรียกใช้งานง่ายขึ้นโดยการซ่อนความซับซ้อนเหล่านี้ไว้ในคลาส Car ดังนี้
class Car {
Engine engine;
Radio radio;
AirCon aircon;
public Car(Engine engine, AirCon airCon, Radio radio) {
this.engine = engine;
this.aircon = airCon;
this.radio = radio;
}
void startCar() {
engine.start();
aircon.turnOn();
radio.turnOn();
}
void stopCar() {
radio.turnOff();
aircon.turnOff();
engine.stop();
}
}
และในการเรียกใช้งานจะเป็นตามตัวอย่างด้านล่าง
package com.company;
public class Main {
public static void main(String[] args) {
Engine engine = new Engine("1600 cc");
AirCon airCon = new AirCon("25 celcious");
Radio radio = new Radio("100 mhz");
Car mycar = new Car(engine,airCon,radio);
System.out.println("My car is "+engine.engine+"/"+airCon.aircon+"/"+radio.radio+".");
System.out.println("======= start car ==========");
mycar.startCar();
System.out.println("======= stop car ==========");
mycar.stopCar();
}
}
จะเห็นว่าคลาส Car นั้นจะลดความซับซ้อนของการใช้งานลงโดยผู้ใช้งานเพียงแค่เรียกใช้เมธอด startCar() ซึ่งจะไปเปิดระบบต่างๆให้ทั้งหมดแทนที่จะต้องไปไล่เปิดเองทีละตัว
My car is 1600 cc/25 celcious/100 mhz.
======= start car ==========
Start engine
Turn on air conditioner
Turn on radio
======= stop car ==========
Turn off radio
Turn off air conditioner
Stop engine