java设计模式之适配器

java设计模式之适配器

虽然学习java也有一段时间,但是初看<< thinking in java >>还是有些吃力,其中的原因是里面的章节有许多设计模式,初看这些设计模式还不能完全深刻领悟其中的道理,于是我决定先简单了解一下java中的一些设计模式.由于本文内容包含自己写的代码,并不能保证能原汁原味反映设计模式的思想.

适配器

  1. 情景引入:假如Tom是数学老师,他自小拥有数学基因,而Jack是体育老师,他自小拥有体育基因.
public interface MathGene {
    void teachMath();
}

public interface SportsGene {
    void teachSports();
}

public class Tom implements MathGene {
    @Override
    public void teachMath() {
        System.out.println("I know math a lots.");
    }
}

public class Jack implements SportsGene {
    @Override
    public void teachSports() {
        System.out.println("I teach sports only!");
    }
}

现有一间学校需要请一个数学老师教数学.

public class NeedMathTeacher {
    void teach(MathGene teacher){
        teacher.teachMath();
    }
}

理论上学校是不会聘请Jack的,怎么能让体育老师教数学呢?但是Jack最近手头很紧,他决定去试一下应聘.但是他需要”改造一下”,让自己像一个数学老师,于是他花了钱去找专业造假的机构Adapter,这个Adapter让那些具有体育基因的人”能教数学”,但其实教数学的时候满脑袋的还是体育知识.

public class Adapter implements MathGene {
    private SportsGene teacher;
    public Adapter(SportsGene teacher){
        this.teacher = teacher;
    }
    @Override
    public void teachMath() {
        teacher.teachSports();
    }
}

经过Adapter后,Jack就可以明目张胆地教数学了.

public class Test {
    public static void main(String[] args) {
        NeedMathTeacher school = new NeedMathTeacher();
        school.teach(new Adapter(new Jack())); // output : I teach sports only!
    }
}

小结

  1. 比如现在一个方法需要一个基类/接口为A类型的对象去做某事,但是现在我只有B类型,那么我可以编写一个实现了A的Adapter,Adapter中有B类型的成员,这个Adapter重写了A类型的方法,而这些方法的内容实际上是包含调用B类型的方法的,然后就可以愉快地拿这个Adapter去当A类型用了.

猜你喜欢

转载自blog.csdn.net/qq_37993487/article/details/80085532