https://hackmd.io/@zxcj04/GAS_SD
介面 | USB | 插座 |
---|---|---|
隨身碟 | 吹風機 | |
光碟機 | 吸塵器 |
只描述一個大概的流程跟邏輯,真正實現的方法交由底下各個裝置去做
interface USBInterface
{
/** 裝置開機 */
public function boot();
/** 裝置是否有連線 */
public function isConnected();
/** 裝置連線不成功的錯誤訊息 */
public function getErrorMessage();
/** 裝置取得電源 */
public function getPower();
/** 裝置取得需要使用到的資料 */
public function getData();
/** 裝置把資料儲存起來 */
public function saveData();
/** 裝置關機 */
public function shutdown();
}
實做
class Mouse implements USBInterface
{
/** 實作 USB 滑鼠的開啟方法 */
public function boot()
{
if ( $this->isBoot() ) {
return "滑鼠開啟成功";
} else {
$this->bootRetry();
}
}
/** 實作其他方法 (略) */
...
}
class Keyboard implements USBInterface
{
/** 實作 USB 鍵盤的開機方法 */
public function boot()
{
if ( $this->bluetoothConnect() )
{
return "已連線到藍芽鍵盤";
} else {
if ( $this->bootKeyboard() )
{
return "鍵盤開啟成功"
}
}
}
/** 實作其他方法 (略) */
...
}
降低耦合性 提高內聚力
example
一本電話簿,裡面有一些聯絡人,聯絡人存著姓名、email,與電話。每當我需要時,就要得到特定格式的『聯絡人清單』。
// Contact.java
public class Contact {
private String name;
private String email;
private String phoneNumber;
public Contact(String name, String email, String phoneNumber) {
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
}
// ...後略
}
// PhoneBook.java
public class PhoneBook {
List<Contact> contacts;
public PhoneBook() {
this.contacts = new ArrayList<>();
}
public String generateFormattedPrint(){
String result = "";
for (Contact contact : contacts){
result += contact.getName() + ": ";
result += contact.getEmail() + " | ";
result += contact.getPhoneNumber() + ". ";
result += "\n";
}
return result;
}
// ...後略
}
類別 PhoneBook 過度依賴 Contact 這個類別
它裡面使用的method全部都是Contact提供的
這件事情嚴重地違反了物件導向的單一職責原則(SRP)
若是聯絡人的內容與輸出格式一旦有換 需要同時更動 Contact 和 PhoneBook
應該修改成
// Contact.java
public class Contact {
// ...前略
public String generateFormattedPrint(){
String result = name + ": ";
result += email + " | ";
result += phoneNumber + ". ";
return result;
}
}
// PhoneBook.java
public class PhoneBook {
List<Contact> contacts;
public PhoneBook() {
this.contacts = new ArrayList<>();
}
public String generateFormattedPrint(){
String result = "";
for (Contact contact : contacts){
result += contact.generateFormattedPrint();
result += "\n";
}
return result;
}
// ...後略
}