日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

【设计模式】—— 适配器模式Adapter

發布時間:2024/4/13 asp.net 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【设计模式】—— 适配器模式Adapter 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  模式意圖

  如果已經有了一種類,而需要調用的接口卻并不能通過這個類實現。因此,把這個現有的類,經過適配,轉換成支持接口的類。

  換句話說,就是把一種現有的接口編程另一種可用的接口。

  模式結構

  【類的適配器】

  Target 目標接口

  Adaptee 現有的類

  Adapter 中間轉換的類,即實現了目標接口,又繼承了現有的類。

1 package com.xingoo.test1; 2 interface Target{ 3 public void operation1(); 4 public void operation2(); 5 } 6 class Adaptee{ 7 public void operation1(){ 8 System.out.println("operation1"); 9 } 10 } 11 12 class Adapter extends Adaptee implements Target{ 13 public void operation2() { 14 System.out.println("operation2"); 15 } 16 } 17 18 public class test { 19 public static void main(String[] args){ 20 Target tar = new Adapter(); 21 tar.operation1(); 22 tar.operation2(); 23 } 24 }

  【對象的適配器】

  與上面不同的是,這次并不是直接繼承現有的類,而是把現有的類,作為一個內部的對象,進行調用。

1 package com.xingoo.test2; 2 3 interface Target{ 4 public void operation1(); 5 public void operation2(); 6 } 7 8 class Adaptee{ 9 public void operation1(){ 10 System.out.println("operation1"); 11 } 12 } 13 14 class Adapter implements Target{ 15 private Adaptee adaptee; 16 public Adapter(Adaptee adaptee){ 17 this.adaptee = adaptee; 18 } 19 public void operation1() { 20 adaptee.operation1(); 21 } 22 23 public void operation2() { 24 System.out.println("operation2"); 25 } 26 27 } 28 public class test { 29 public static void main(String[] args){ 30 Target tar = new Adapter(new Adaptee()); 31 tar.operation1(); 32 tar.operation2(); 33 } 34 }

  使用場景

  1 想使用一個已經存在的類,但是它的接口并不符合要求

  2 想創建一個可以復用的類,這個類與其他的類可以協同工作

  3 想使用已經存在的子類,但是不可能對每個子類都匹配他們的接口。因此對象適配器可以適配它的父類接口。(這個沒理解,以后慢慢琢磨)

  生活中的設計模式

  俗話說,窈窕淑女君子好逑,最近看跑男,十分迷戀Baby。

  但是,如果桃花運淺,身邊只有鳳姐,那么也不需要擔心。

  只需要簡單的化妝化妝,PS一下,美女鳳姐,依然無可替代!

  

  雖然,沒有AngleBaby,但是我們有鳳姐,所以依然可以看到AngleBaby甜美的笑。

?

1 package com.xingoo.test3; 2 interface BeautifulGirl{ 3 public void Smiling(); 4 } 5 class UglyGirl{ 6 public void Crying(){ 7 System.out.println("我在哭泣..."); 8 } 9 } 10 class ApplyCosmetics implements BeautifulGirl{ 11 private UglyGirl girl; 12 public ApplyCosmetics(UglyGirl girl){ 13 this.girl = girl; 14 } 15 public void Smiling() { 16 girl.Crying(); 17 } 18 } 19 public class test { 20 public static void main(String[] args){ 21 BeautifulGirl girl = new ApplyCosmetics(new UglyGirl()); 22 girl.Smiling(); 23 } 24 }

  運行結果

我在哭泣...

?

本文轉自博客園xingoo的博客,原文鏈接:【設計模式】—— 適配器模式Adapter,如需轉載請自行聯系原博主。

總結

以上是生活随笔為你收集整理的【设计模式】—— 适配器模式Adapter的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。