设计模式(适配器模式)
创始人
2024-05-25 22:33:41

设计模式(适配器模式)

第二章 设计模式之适配器模式(Adapter)

一、Adapter模式介绍

在这里插入图片描述
适配器模式位于实际情况和需求之间,填补两者之间的差距。

二、示例程序1(使用继承的适配器)

1.示例程序示意图

在这里插入图片描述
程序表示输入hello字符串,输出为(hello)或者*hello*的简单程序。
扮演适配器角色的是PrintBanner类。该类继承了Banner类并实现了“需求”–Print接口。

2.Banner类

package cn.pp.adapter.extend;public class Banner {private String str;public Banner(String str) {this.str = str;}public void showWithParen() {System.out.println("(" + str + ")");}public void showWithAster() {System.out.println("*" + str + "*");}
}

3.Print类

public interface Print {public void printWeak();public void printStrong();
}

4.PrintBannerAdapter类

public class PrintBannerAdapter extends Banner implements Print {public PrintBannerAdapter(String str) {super(str);}@Overridepublic void printWeak() {showWithParen();}@Overridepublic void printStrong() {showWithAster();}
}

5.Main类

   public static void main(String[] args) {Print print = new PrintBannerAdapter("我是适配器");print.printStrong();print.printWeak();}

二、示例程序2(使用委托的适配器)

1.示例程序示意图

在这里插入图片描述
如果类Print不是一个接口而是一个类,由于java不能多继承,所以只有采用委托的适配器模式。
PrintBanner类中的banner字段保存了Banner类的示例,通过构造函数注入。

2.Banner类

package cn.pp.adapter.extend;public class Banner {private String str;public Banner(String str) {this.str = str;}public void showWithParen() {System.out.println("(" + str + ")");}public void showWithAster() {System.out.println("*" + str + "*");}
}

3.Print类

public abstract class Print {public abstract  void printWeak();public abstract  void printStrong();
}

4.PrintBannerAdapter类

public class PrintBannerAdapter extends Print {private Banner banner;public PrintBannerAdapter(String str) {this.banner = new Banner(str);}@Overridepublic void printWeak() {banner.showWithParen();}@Overridepublic void printStrong() {banner.showWithAster();}
}

5.Main类

   public static void main(String[] args) {Print print = new PrintBannerAdapter("我是适配器");print.printStrong();print.printWeak();}

相关内容

热门资讯

世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...