侧边栏壁纸
博主头像
Shawe`Blog博主等级

正确的思维是创造一切的前提。

  • 累计撰写 33 篇文章
  • 累计创建 4 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

Java设计模式 - 模板模式

在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。

关注定义算法的框架,将算法的具体实现延迟到子类中。

模板模式(Template Pattern)是一种行为设计模式,它定义了一个算法的框架,并允许子类重写其中的某些步骤,而不改变该算法的结构。模板模式在父类中定义了算法的基本步骤,具体的实现延迟到子类中。

下面是一个用Java代码示例实现模板模式的简单示例:

// 抽象模板类
abstract class Recipe {
    public void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        if (customerWantsCondiments()) {
            addCondiments();
        }
    }

    public void boilWater() {
        System.out.println("Boiling water");
    }

    public abstract void brew();

    public void pourInCup() {
        System.out.println("Pouring into cup");
    }

    // 钩子方法,子类可以选择是否覆盖
    public boolean customerWantsCondiments() {
        return true;
    }

    public abstract void addCondiments();
}

// 具体实现类1
class CoffeeRecipe extends Recipe {
    public void brew() {
        System.out.println("Dripping coffee through filter");
    }

    public void addCondiments() {
        System.out.println("Adding sugar and milk");
    }
}

// 具体实现类2
class TeaRecipe extends Recipe {
    public void brew() {
        System.out.println("Steeping the tea");
    }

    public void addCondiments() {
        System.out.println("Adding lemon");
    }

    public boolean customerWantsCondiments() {
        return false; // 茶不需要添加调料
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        Recipe coffeeRecipe = new CoffeeRecipe();
        coffeeRecipe.prepareRecipe();

        Recipe teaRecipe = new TeaRecipe();
        teaRecipe.prepareRecipe();
    }
}

在上述示例中,Recipe 是抽象模板类,定义了准备食谱的基本步骤,包括煮水、冲泡、倒入杯子和添加调料。CoffeeRecipeTeaRecipe 是具体的实现类,分别实现了冲泡咖啡和泡茶的具体步骤。

模板模式的优点如下:

  1. 提高了代码复用性:将公共的算法步骤放在父类中,减少重复代码。

  2. 提供了扩展点:子类可以重写父类中的某些步骤,以提供特定实现。

  3. 降低了耦合度:父类控制算法的框架,子类负责实现具体步骤,降低了类之间的耦合度。

模板模式的缺点如下:

  1. 可能导致代码膨胀:如果算法框架过于复杂,可能会导致代码膨胀。

  2. 不便于扩展新的算法:需要修改父类代码来添加新的算法步骤,可能影响其他子类。

适合使用模板模式的场景包括:

  1. 当有多个类共享相同的算法框架,但其中某些步骤有所差异时,可以使用模板模式。

  2. 当需要控制算法的整体流程,但允许子类提供特定实现时,可以使用模板模式。

  3. 当希望避免重复代码,提高代码复用性时,可以使用模板模式。

总结来说,模板模式通过定义一个算法的框架,并延迟具体实现到子类中,提高了代码复用性和灵活性。适合在多个类共享相同算法框架但部分步骤有所不同的场景下使用。

0

评论区