之前學(xué)習(xí)的是命令模式
對于命令模式的理解
命令模式就是將操作封裝為一個(gè)類(一個(gè)命令)。在通過一個(gè)控制器把命令封裝進(jìn)去,就像一個(gè)遙控器,最后通過不同的命令就可以實(shí)現(xiàn)不同的操作
一、 對適配器模式和觀察者模式的理解
適配器模式就是改變一個(gè)接口,實(shí)現(xiàn)不同的操作。就像插座轉(zhuǎn)換頭一樣,將三孔插座轉(zhuǎn)換為二孔插座。
外觀模式字面上就是好的形象的意識。將一些操作集合在一起,統(tǒng)一調(diào)用,簡單又方便。就像家里面的插頭到處都是。我們可以把所有的插頭都插在一個(gè)大插板上面。每次使用的時(shí)候,就可以只用開、關(guān)大插板就可以。不用每次都插很多插頭。
二、代碼實(shí)現(xiàn)
適配器模式
三孔插座
// 三孔插座
public interface SocketThree {
public void chargeThree();
}
class SocketThreeImpl implements SocketThree{
@Override
public void chargeThree() {
System.out.println("三孔插座");
}
}
兩孔插座
// 兩孔插座
public interface SocketTwo {
public void chargeTwo();
}
class SocketTwoImpl implements SocketTwo{
@Override
public void chargeTwo() {
System.out.println("兩孔插座");
}
}
插座適配器
// 插座適配器 將三孔插座轉(zhuǎn)換為二孔插座, 看著像二孔,但是實(shí)際上還是三孔
public class SocketAdapter implements SocketTwo{
SocketThree socketThree;
public SocketAdapter(SocketThree socketThree) {
this.socketThree = socketThree;
}
@Override
public void chargeTwo() {
System.out.println("轉(zhuǎn)換后的兩孔插座");
this.socketThree.chargeThree();
}
}
main方法運(yùn)行
// 適配器模式
SocketThree st = new SocketThreeImpl();
st.chargeThree();
// 通過轉(zhuǎn)換器將三孔插座轉(zhuǎn)換為兩孔插座
SocketTwo stwo = new SocketAdapter(st);
stwo.chargeTwo();
運(yùn)行結(jié)果
三孔插座
轉(zhuǎn)換后的兩孔插座
三孔插座
外觀模式
新建電視、電燈、烤火爐類
public class TV {
public void on() {
System.out.println("開電視");
}
public void off() {
System.out.println("關(guān)電視");
}
}
class Light{
public void on() {
System.out.println("開電燈");
}
public void off() {
System.out.println("關(guān)電燈");
}
}
class Stove{
public void on() {
System.out.println("開火爐");
}
public void off() {
System.out.println("關(guān)火爐");
}
}
大插板(不讓插頭凌亂,外觀好看)
// 買了一個(gè)大插板,將電視、烤火爐、電燈的插頭都插在這個(gè)大插板上面
public class FacadeSocket {
TV tv;
Light light;
Stove stove;
public FacadeSocket(TV tv,Light light,Stove stove) {
this.tv = tv;
this.light = light;
this.stove = stove;
}
// 通過外觀模式統(tǒng)一處理
public void on() {
this.tv.on();
this.light.on();
this.stove.on();
}
public void off() {
this.tv.off();
this.light.off();
this.stove.off();
}
}
main方法實(shí)現(xiàn)
public static void main(String srgs[]){
// 外觀模式
TV tv = new TV();
Light light = new Light();
Stove stove = new Stove();
// 創(chuàng)建大插板, 統(tǒng)一開關(guān)
FacadeSocket fs = new FacadeSocket(tv, light,stove);
fs.on();
fs.off();
}
運(yùn)行結(jié)果
開電視
開電燈
開火爐
關(guān)電視
關(guān)電燈
關(guān)火爐
三、UML類圖

適配器模式

外觀模式
四、筆記
oo設(shè)計(jì)原則
封裝變化
依賴接口編程,不依賴實(shí)現(xiàn)編程
為交互對象之間的松耦合設(shè)計(jì)而努力
對修改關(guān)閉、對擴(kuò)展開放
多用組合,少用繼承
依賴抽象、不依賴具體類
只和朋友交談
適配器模式定義:
將一個(gè)類的接口,轉(zhuǎn)移成為可以期望的另一個(gè)接口。適配器讓原本不兼容的兩個(gè)類可以合作無間
外觀模式定義:
提供類一個(gè)統(tǒng)一的接口,用來訪問子系統(tǒng)中的一群接口。外觀定義類一個(gè)高層接口,讓子系統(tǒng)更容易使用。
end