东三省网站建设公司,上海华谊集团建设有限公司网站,成全视频免费观看在线观看高清动漫,宁波网站优化公司设计模式#xff08;适配器模式#xff09;
第二章 设计模式之适配器模式#xff08;Adapter#xff09;
一、Adapter模式介绍 适配器模式位于实际情况和需求之间#xff0c;填补两者之间的差距。
二、示例程序1#xff08;使用继承的适配器#xff09;
1.示例程序示…设计模式适配器模式
第二章 设计模式之适配器模式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();}