《Java設計模式》之面板模式__Java

來源:互聯網
上載者:User
 面板模式(Facade pattern)涉及到子系統的一些類。所謂子系統,是為提供一系列相關的特徵(功能)而緊密關聯的一組類。例如,一個Account類、Address類和CreditCard類相互關聯,成為子系統的一部分,提供線上客戶的特徵。

  在真實的 應用 系統中,一個子系統可能由很多類組成。子系統的客戶為了它們的需要,需要和子系統中的一些類進行互動。客戶和子系統的類進行直接的互動會導致用戶端對象和子系統(Figure1)之間高度耦合。任何的類似於對子系統中類的介面的修改,會對依賴於它的所有的客戶類造成影響。

   
Figure1: Client Interaction with Subsystem Classes before Applying the Facade Pattern

  面板模式(Facade pattern)很適用於在上述情況。面板模式(Facade pattern)為子系統提供了一個更高層次、更簡單的介面,從而降低了子系統的複雜度和依賴。這使得子系統更便於使用和管理。

  外觀是一個能為子系統和客戶提供簡單介面的類。當正確的套用面板,客戶不再直接和子系統中的類互動,而是與外觀互動。外觀承擔與子系統中類互動的責任。實際上,外觀是子系統與客戶的介面,這樣面板模式降低了子系統和客戶的耦合度(Figure2). 

   
Figure2: Client Interaction with Subsystem Classes after Applying the Facade Pattern

  從Figure2中我們可以看到:外觀對象隔離了客戶和子系統對象,從而降低了耦合度。當子系統中的類進行改變時,用戶端不會像以前一樣受到影響。

  儘管客戶使用由外觀提供的簡單介面,但是當需要的時候,用戶端還是可以視外觀不存在,直接存取子系統中的底層次的介面。這種情況下,它們之間的依賴/耦合度和原來一樣。 

  例子:

  讓我們建立一個應用:

  (1) 接受客戶的詳細資料(賬戶、地址和信用卡資訊)

  (2) 驗證輸入的資訊

  (3) 儲存輸入的資訊到相應的檔案中。

  這個應用有三個類:Account、Address和CreditCard。每一個類都有自己的驗證和儲存資料的方法。

  Listing1: AccountClass 

public class Account { 
 String firstName; 
 String lastName; 
 final String ACCOUNT_DATA_FILE = "AccountData.txt"; 
 public Account(String fname, String lname) { 
  firstName = fname; 
  lastName = lname; 
 } 
 public boolean isValid() { 
  /* 
  Let's go with simpler validation 
  here to keep the example simpler. 
  */ 
  … 
  … 
 } 
 public boolean save() { 
  FileUtil futil = new FileUtil(); 
  String dataLine = getLastName() + ”," + getFirstName(); 
  return futil.writeToFile(ACCOUNT_DATA_FILE, dataLine,true, true); 
 } 
 public String getFirstName() { 
  return firstName; 
 } 
 public String getLastName() { 
  return lastName; 
 } 
}

  Listing2: Address Class 

public class Address { 
 String address; 
 String city; 
 String state; 
 final String ADDRESS_DATA_FILE = "Address.txt"; 
 public Address(String add, String cty, String st) { 
  address = add; 
  city = cty; 
  state = st; 
 } 
 public boolean isValid() { 
  /* 
  The address validation algorithm 
  could be complex in real-world 
  applications. 
  Let's go with simpler validation 
  here to keep the example simpler. 
  */ 
  if (getState().trim().length() < 2) 
   return false; 
  return true; 
 } 
 public boolean save() { 
  FileUtil futil = new FileUtil(); 
  String dataLine = getAddress() + ”," + getCity() + ”," + getState(); 
  return futil.writeToFile(ADDRESS_DATA_FILE, dataLine,true, true); 
 } 
 public String getAddress() { 
  return address; 
 } 
 public String getCity() { 
  return city; 
 } 
 public String getState() { 
  return state; 
 } 
}

  Listing3: CreditCard Class 

public class CreditCard { 
 String cardType; 
 String cardNumber; 
 String cardExpDate; 
 final String CC_DATA_FILE = "CC.txt"; 
 public CreditCard(String ccType, String ccNumber, 
 String ccExpDate) { 
  cardType = ccType; 
  cardNumber = ccNumber; 
  cardExpDate = ccExpDate; 
 } 
 public boolean isValid() { 
  /* 
  Let's go with simpler validation 
  here to keep the example simpler. 
  */ 
  if (getCardType().equals(AccountManager.VISA)) { 
   return (getCardNumber().trim().length() == 16); 
  } 
  if (getCardType().equals(AccountManager.DISCOVER)) { 
   return (getCardNumber().trim().length() == 15); 
  } 
  if (getCardType().equals(AccountManager.MASTER)) { 
   return (getCardNumber().trim().length() == 16); 
  } 
  return false; 
 } 
 public boolean save() { 
  FileUtil futil = new FileUtil(); 
  String dataLine = getCardType() + ,”" + getCardNumber() + ”," + getCardExpDate(); 
  return futil.writeToFile(CC_DATA_FILE, dataLine, true, true); 
 } 
 public String getCardType() { 
  return cardType; 
 } 
 public String getCardNumber() { 
  return cardNumber; 
 } 
 public String getCardExpDate() { 
  return cardExpDate; 
 } 
}

  
Figure3: Subsystem Classes to Provide the Necessary Functionality to Validate and Save the Customer Data


 讓我們建立一個客戶AccountManager,它提供使用者輸入資料的使用者介面。

  Listing4: Client AccountManager Class 

public class AccountManager extends JFrame { 
 public static final String newline = "\n"; 
 public static final String VALIDATE_SAVE = "Validate & Save"; 
 … 
 … 
 public AccountManager() { 
  super(" Facade Pattern - Example "); 
  cmbCardType = new JComboBox(); 
  cmbCardType.addItem(AccountManager.VISA); 
  cmbCardType.addItem(AccountManager.MASTER); 
  cmbCardType.addItem(AccountManager.DISCOVER); 
  … 
  … 
  //Create buttons 
  JButton validateSaveButton = new JButton(AccountManager.VALIDATE_SAVE); 
  … 
  … 
 } 
 public String getFirstName() { 
  return txtFirstName.getText(); 
 } 
 … 
 … 
}//End of class AccountManager

  當客戶AccountManage啟動並執行時候,展示的使用者介面如下:

  
Figure4: User Interface to Enter the Customer Data

  為了驗證和儲存輸入的資料,客戶AccountManager需要:

  (1) 建立Account、Address和CreditCard對象。 

  (2) 用這些對象驗證輸入的資料

  (3) 用這些對象儲存輸入的資料。

  下面是對象間的互動順序圖:

 
Figure5: How a Client Would Normally Interact (Directly) with Subsystem Classes to Validate and Save the Customer Data

  在這個例子中 應用 面板模式是一個很好的設計,它可以降低客戶和子系統組件(Address、Account和CreditCard)之間的耦合度。套用面板模式,讓我們定義一個外觀類CustomerFacade (Figure6 and Listing5)。它為由客戶資料處理類(Address、Account和CreditCard)所組成的子系統提供一個高層次的、簡單的介面。 

CustomerFacade 
address:String 
city:String 
state:String 
cardType:String 
cardNumber:String 
cardExpDate:String 
fname:String 
lname:String 
setAddress(inAddress:String) 
setCity(inCity:String) 
setState(inState:String) 
setCardType(inCardType:String) 
setCardNumber(inCardNumber:String) 
setCardExpDate(inCardExpDate:String) 
setFName(inFName:String) 
setLName(inLName:String) 
saveCustomerData()

   
Figure6: Facade Class to Be Used by the Client in the Revised Design

  Listing5: CustomerFacade Class 

public class CustomerFacade { 
 private String address; 
 private String city; 
 private String state; 
 private String cardType; 
 private String cardNumber; 
 private String cardExpDate; 
 private String fname; 
 private String lname; 
 public void setAddress(String inAddress) { 
  address = inAddress; 
 } 
 public void setCity(String inCity) { 
  city = inCity; 
 } 
 public void setState(String inState) { 
  state = inState; 
 } 
 public void setFName(String inFName) { 
  fname = inFName; 
 } 
 public void setLName(String inLName) { 
  lname = inLName; 
 } 
 public void setCardType(String inCardType) { 
  cardType = inCardType; 
 } 
 public void setCardNumber(String inCardNumber) { 
  cardNumber = inCardNumber; 
 } 
 public void setCardExpDate(String inCardExpDate) { 
  cardExpDate = inCardExpDate; 
 } 
 public boolean saveCustomerData() { 
  Address objAddress; 
  Account objAccount; 
  CreditCard objCreditCard; 
  /* 
   client is transparent from the following 
   set of subsystem related operations. 
  */ 
  boolean validData = true; 
  String errorMessage = ""; 
  objAccount = new Account(fname, lname); 
  if (objAccount.isValid() == false) { 
   validData = false; 
   errorMessage = "Invalid FirstName/LastName"; 
  } 
  objAddress = new Address(address, city, state); 
  if (objAddress.isValid() == false) { 
   validData = false; 
   errorMessage = "Invalid Address/City/State"; 
  } 
  objCreditCard = new CreditCard(cardType, cardNumber, cardExpDate); 
  if (objCreditCard.isValid() == false) { 
   validData = false; 
   errorMessage = "Invalid CreditCard Info"; 
  } 
  if (!validData) { 
   System.out.println(errorMessage); 
   return false; 
  } 
  if (objAddress.save() && objAccount.save() && objCreditCard.save()) { 
   return true; 
  } else { 
   return false; 
  } 
 } 
}

  CustomerFacade類以saveCustomData方法的形式提供了業務層次上的服務。客戶AccountManager不是直接和子系統的每一個組件互動,而是使用了由CustomFacade對象提供的驗證和儲存客戶資料的更高層次、更簡單的介面(Figure7).

 
Figure7: Class Association with the Fa?ade Class in Place 。

  在新的設計中,為了驗證和儲存客戶資料,客戶需要:

  (1) 建立或獲得外觀對象CustomFacade的一個執行個體。

  (2) 傳遞資料給CustomFacade執行個體進行驗證和儲存。

  (3) 調用CustomFacade執行個體上的saveCustomData方法。

  CustomFacade處理建立子系統中必要的對象並且調用這些對象上相應的驗證、儲存客戶資料的方法這些細節問題。客戶不再需要直接存取任何的子系統中的對象。

  Figure8展示了新的設計的訊息流程圖:

 
Figure 22.8: In the Revised Design, Clients Interact with the Fa?ade Instance to Interface with the Subsystem

   重要提示 :

  下面是套用面板模式的注意事項:

  (1) 在設計外觀時,不需要增加額外的功能。

  (2) 不要從外觀方法中返回子系統中的組件給客戶。例如:有一個下面的方法:

  CreditCard getCreditCard() 

  會報漏子系統的細節給客戶。應用就不能從套用面板模式中取得最大的好處。

  (3)套用面板的目的是提供一個高層次的介面。因此,外觀方法最適合提供特定的高層次的商務服務,而不是進行底層次的單獨的業務執行。

以上是一個比較全面的例子,另外,為了加深理解我們繼續學習下面的內容。

 相關角色:

         1.外觀(Facade)角色:用戶端可以調用這個角色的方法。此角色知曉相關的子系統的功能和責任。

         2.子系統角色:可以同時有一個或者多個子系統。每一個子系統都不是一個單獨的類,而是一個類的集合。每一個子系統都可以被用戶端直接調用,或者被外觀角色調用。

    適用情況:

         1.為複雜的子系統提供一個簡單的介面;

         2.客戶程式與抽象類別的實現部分之間存在著很大的依賴性;

         3.構建一個階層的子系統時,適用面板模式定義子系統中每層的進入點。

    面板模式的簡單實現:

 

代碼:

Camara.java

package facade;public class Camara {public void turnOn(){System.out.println("開啟網路攝影機。");}public void turnOff(){System.out.println("關閉網路攝影機。");}} 

Light.java

package facade;public class Light {public void turnOn(){System.out.println("開燈。");}public void turnOff(){System.out.println("關燈。");}}
Sensor.java

package facade;public class Sensor {public void activate(){System.out.println("開啟感應器。");}public void deactivate(){System.out.println("關閉感應器。");}}

MyFacade.java

package facade;public class MyFacade {private static Camara c1, c2;private static Light l1, l2, l3;private static Sensor s;static{c1 = new Camara();c2 = new Camara();l1 = new Light();l2 = new Light();l3 = new

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.