如有雷同,请原谅我的无耻,因为我不是代码的生产者,只是代码的搬运工。部分内容来自,图解设计模式,一书。
何为设计模式?百度百科这样解释道:
设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。使用设计模式的目的:为了代码可重用性、让代码更容易被他人理解、保证代码可靠性。 设计模式使代码编写真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。
其实,说白了设计模式就是一套程序员在日程生活中用来写出优美代码的同时保证代码高可靠性以及高可用性的模板,或者说是一种全新的开发思路。当然除此之外,更重要的一点,我们时不时的还可以拿设计模式,来与三两比我们还菜的菜鸟来吹牛逼,以显示我们的高逼格。
当然今天,我可不是为了向小伙伴们吹牛逼来的,我是以一种谦卑的姿态来和大家共同探讨共同学习共同进步的心态,来谈论一下Adapter模式的。
废话至此结束,现在切入正题。Adapter模式即适配器模式,它是一种用于填补"现有的程序"和"所需的程序之间差异"的设计模式,又称Wrapper模式。如果这样讲的话,可能部分像我一样脑子慢的同学会不太理解。那么,让我们看一个现实生活中血淋林的例子,或许你就会豁然开朗,呀!原来这就是tmd适配器模式。
如果我想让额定工作电压是直流12v的笔记本在交流220v的交流电压下生活并工作,我该怎么办?可能调皮的同学会说,没事我的笔记本有电池即使不用220v的交流电也能工作,但是电池总有用完的一天。当然,聪明的同学可能会说,使用适配器来弥补两者之间的差异,对就是适配器。同样的,该模式一样始于两段程序之间。
让我们动起手来,撸两行代码,不对是抄写两行代码。可能有些同学会反对我的这种做法,但是我想要说的是,只有你抄写的足够多代码,手感才能上来才能写两行属于自己的代码。如果你只是看,但是你永远不会写,纸上得来总觉浅,绝知此事要躬行。说明:Banner类是我们的220v交流电压,Print接口是我们的笔记本,PrintBanner继承了Banner类同时实现了Print接口,即为我们的适配器,Main就是主程序了。好了,自己去慢慢体会与感悟吧。
public class Banner{
private String string;
public Banner(String string){
this.string=string;
}
public void showWithParen(){
System.out.println("("+string+")");
}
public void showWithAster(){
System.out.println("*"+string+"*");
}
private String string;
public Banner(String string){
this.string=string;
}
public void showWithParen(){
System.out.println("("+string+")");
}
public void showWithAster(){
System.out.println("*"+string+"*");
}
}
public interface Print{
public abstract void printWeak();
public abstract void printStrong();
}
public class PrintBanner extends Banner implements Print{
public PrintBanner(String string){
public PrintBanner(String string){
super(string);
}
public void printWeak(){
showWithParen();
}
public void printStrong(){
showWithAster();
}
}
}
public void printWeak(){
showWithParen();
}
public void printStrong(){
showWithAster();
}
}
public class Main{
public static void main(String[]args){
Print p=new PrintBanner("hello");
p.printWeak();
p.printStrong();
}
public static void main(String[]args){
Print p=new PrintBanner("hello");
p.printWeak();
p.printStrong();
}
}