版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaofather/article/details/85157363
1. 深入理解适配器模式
1.1 适配器模式的理念:提高兼容性,解耦
1.2 命题:
1 商人需要钢,但是供货商只能提供铁,此时要怎样得到自己的需求?(类的适配器模式)
1.1 创建供货商
class tource {
public void method1() {
System.out.println("this is original method!");
}
}
1.2 定义你想要得到的钢,以及炼钢方式
// 你的目标
interface targatable{
public void method1();
public void method2();
}
// 适配器
class Adapter extends tource implements targatable {
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
1.3 拿到钢
public class source{
public static void main(String[] args) {
targatable target = new Adapter();
target.method1();
target.method2();
}
}
2 商人觉得自己做事太死板,想灵活一点,商人怎样达到自己的需求?(对象的适配器模式)
2.1 创建供货商
class aource {
public void method1() {
System.out.println("this is original method!");
}
}
2.2 定义你想要得到的钢,以及炼钢方式
interface aargatable{
public void method1();
public void method2();
}
// 适配器
class aadapter implements aargatable {
private aource aou;
public aadapter(aource source){
this.aou = source;
}
public void method2() {
System.out.println("this is the targetable method!");
}
public void method1() {
aou.method1();
}
}
2.3 拿到钢
public class source2 {
public static void main(String[] args) {
aource source = new aource();
aargatable target = new aadapter(source);
target.method1();
target.method2();
}
}
3 商人赚了钱,觉得以上方式固然拿到了钢,但是觉得还是不够灵活,总是让我提供某以方面,何不综合利用一下,供货商有铁,商人提供锻造的渠道,锻造渠道的人来找商人,商人提供铁,这样就能物尽所用(接口的适配器模式:多减少补)
扫描二维码关注公众号,回复:
4589769 查看本文章
3.1 商人定义目标并定义配合方式
interface Sourceable {
public void method1();
public void method2();
}
// 定义抽象类,实现该接口
abstract class Wrapper2 implements Sourceable{
public void method1(){}
public void method2(){}
}
3.2 很多供货商看到了配合方式,觉得自己有例可图,都联系上商人
// 重写抽象类
class SourceSub1 extends Wrapper2 {
public void method1(){
System.out.println("the SourceSub1's first Sub1!");
}
}
class SourceSub2 extends Wrapper2 {
public void method2(){
System.out.println("the SourceSub2's second Sub2!");
}
}
3.3 拿到钢
public class source3 {
public static void main(String[] args) {
Sourceable source1 = new SourceSub1();
source1.method1();
source1.method2();
Sourceable source2 = new SourceSub2();
source2.method1();
source2.method2();
}
}
2.适配器模式运用的场合
2.1 你想涨薪水,除了自身的努力外,你需要时间和知识,你觉得自己够努力,知识也能在互联网找到,但是你总是加班,这种情况下你还是考虑下怎么调整
2.2 多减少补(这个很厉害的)