1 介紹
續(xù)上篇《大/小白祝大家元旦Glücklich》
小白:老板,這件衣服多少錢哇?
老板:這件衣服500大洋。
小白:這麼貴??。
Acey:等等小白,我有會員卡哦。
小白:這張卡....我服,,???,,。
老板:小鵬友,這張是鉆石會員,可以打9折哦。
小白:那就是450塊咯,瞬間省了50大洋,謝謝大哥。??
Acey:木事木事。其實會員卡和適配器模式還是比較類似的啦。
適配器模式:Adapter模式是構造型模式的一種,可以改變已存在類(或外部組件)的接口形式。
小白:這個樣子呀,會員卡可以有好幾個等級,這就是適配嘛?
Acey:對呢,會員卡就是對衣服售價(外部組件)功能的一個擴充,而普通會員,高級會員就是對會員卡的一個適配,當然商家也可以繼續(xù)添加鉆石會員等。
小白:這樣我們就可以拿著會員卡打相應的折扣啦。
2 實現(xiàn)
第一步:創(chuàng)建衣服
Clothes.class
public class Clothes {
//衣服價錢
private Integer price = 500;
public void sale(){
System.out.println("衣服原價:" + price);
}
public Integer getPrice() {
return price;
}
}
第二步:創(chuàng)建VIP適配器
Adapter.class
public class Adapter {
private Clothes clothe;
//獲取衣服信息
public Adapter(Clothes clothe) {
this.clothe = clothe;
}
//一級會員
public void VIP1(){
this.clothe.sale();
System.out.println("您的卡為VIP1,打9折,打折后的價格為:" + 0.9 * this.clothe.getPrice());
}
//二級會員
public void VIP2(){
this.clothe.sale();
System.out.println("您的卡為VIP2,打7折,打折后的價格為:" + 0.7 * this.clothe.getPrice());
}
}
第三步:測試
MainClass.class
public class MainClass {
public static void main(String[] args) {
Adapter adapter = new Adapter(new Clothes());
//打折
adapter.VIP1();
}
}
運行結果
Acey:這樣實現(xiàn)后可以將目標類和適配器解耦,一方需要改動時另一方無需改動。而且一個適配器可以適配多個目標類,即一張會員卡購買商場內(nèi)的東西都是打折扣的。當然了也可以多個適配器同時適配一個目標類。
.
喜歡的話戳一下喜歡唄。
有什么建議的話希望大家能在下方回復??
上一篇:《大/小白祝大家元旦Glücklich》
下一篇:《解釋器模式 - 明天考試,戳不輟進來你自己看著辦》(待更)