适配器 Adapter

  • 现实类比:类似于笔记本电脑电源适配器,可以将 220V 电压转化为笔记本电脑可用的 12V 电压。
  • 相关角色:

    • 请求者 Client:使用 Target (笔记本电脑);
    • 适配对象 Target:定义需要方法的接口或类(12V 电源);
    • 被适配对象 Adaptee:持有已有可用方法的类(220V 电源);
    • 适配器 Adapter:利用被适配对象持有的方法适配成适配对象需要的方法(电源适配器)。

      继承适配器

      image.png

      1. class Adapter extends Adaptee implements Target {
      2. public Adapter() {
      3. super();
      4. }
      5. public void targetMethod() {
      6. methodA();
      7. }
      8. }

      适配器通过 Adaptee 中的方法来支持 Target 的需求,在 Client 中使用 Target 引用 Adapter 实例并使用其提供的方法。

      委托适配器

      image.png

      1. class Adapter extends Target {
      2. private Adaptee adaptee;
      3. public Adapter() {
      4. this.adaptee = new Adaptee();
      5. }
      6. public void targetMethod() {
      7. adaptee.methodA();
      8. }
      9. }

      适配器通过使用 Adaptee 实例可用的方法来支持 Target 的需求,在 Client 中使用 Target 饮用 Adapter 实例并使用其提供的方法。

      模板 Template

  • 现实类比:使用不同的笔临摹同样的字帖模板。

  • 相关角色:
    • 抽象类 AbstractClass:实现模板负责的统一方法,声明统一待实现的抽象方法(字帖模板);
    • 具体类 ConcreteClass:独立实现抽象方法,作为被 AbstractClass 引用的实例(用不同的笔临摹)。
  • 其他要点:无论父类类型的变量中引用的是什么类的实例,都不影响代码工作(满足了李氏替换原则,可以用子类的地方一定可以使用父类)。

image.png

  1. // 模板抽象类
  2. public abstract class AbstractClass {
  3. public abstract void independentMethod();
  4. public final void uniformMethod() {
  5. independentMethod();
  6. // do something else...
  7. }
  8. }
  9. // 具体实现类
  10. public class ConcreteClass extends AbstractClass{
  11. public ConcreteClass() {}
  12. public void independentMethod() {
  13. // do something this class should do
  14. }
  15. }

工厂 Factory

  • 现实类比:使用模板生产实例
  • 相关角色:
    • 抽象产品 Product:宝贝(抽象类);
    • 抽象工厂 Factory:(抽象类);
    • 具体商品 ConcreteProduct:(具体类);
    • 具体工厂 ConcreteFactory:(具体类)。