模板方法模式(Template Method Pattern)

模板方法(Template Method)模式定义:

Define the skeleton of an algorithm in an operation , deferring some steps to subclasses . Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure .

定义一个操作中的一个算法框架,把一些步骤推迟到子类去实现。模板方法模式让子类不需要改变算法结构而重新定义特定的算法步骤。

也就是说:模板方法模式定义了一系列算法步骤,子类可以去实现或覆盖其中某些步骤,但不能改变这些步骤的执行顺序。

下面的代码是模板方法模式的示例代码,类HappyPeople的方法celebrateSpringFestival()是一个模板方法,有3个步骤,其中方法travel()是抽象部分,用于子类实现不同客户化逻辑。

package pattern.part1.chapter2.template;

/**
 * Date: 2009-11-18
 * Time: 0:42:25
 */
public class HappyPeopleTestDrive {
    public static void main(String[] args) {
        HappyPeople passengerByAir = new PassengerByAir();
        HappyPeople passengerByCoach = new PassengerByCoach();
        HappyPeople passengerByTrain = new PassengerByTrain();

        System.out.println("Let's Go Home For A Grand Family Reunion...\n");

        System.out.println("Tom is going home:");
        passengerByAir.celebrateSpringFestival();

        System.out.println("\nRoss is going home:");
        passengerByCoach.celebrateSpringFestival();

        System.out.println("\nCatherine is going home:");
        passengerByTrain.celebrateSpringFestival();
    }
}

package pattern.part1.chapter2.template;


public abstract class HappyPeople {
    public void celebrateSpringFestival() {
        subscribeTicket();
        travel();
        celebrate();
    }

    protected final void subscribeTicket() {
        //Buying ticket...
        System.out.println("Buying ticket...");
    }

    protected abstract void travel();

    protected final void celebrate() {
        //Celebrating Chinese New Year...
        System.out.println("Happy Chinese New Year!");
    }
}

package pattern.part1.chapter2.template;

/**
 * Date: 2009-11-18
 * Time: 0:23:43
 */
public class PassengerByAir extends HappyPeople {
    @Override
    protected void travel() {
        //Traveling by Air...
        System.out.println("Travelling by Air...");
    }
}

package pattern.part1.chapter2.template;

/**
 * Date: 2009-11-18
 * Time: 0:22:16
 */
public class PassengerByCoach extends HappyPeople {
    @Override
    protected void travel() {
        //Travel by Coach...
        System.out.println("Travelling by Coach...");
    }
}

package pattern.part1.chapter2.template;

/**
 * Date: 2009-11-18
 * Time: 0:20:05
 */
public class PassengerByTrain extends HappyPeople {
    @Override
    protected void travel() {
        //Travel by Train...
        System.out.println("Travelling by Train...");
    }
}

模版方法模式可以解决某些场景中的代码冗余问题,但也可能引入类的泛滥问题。使用回调可以避免类的泛滥。

回调表示一段可执行逻辑的引用(或者指针),我们把该引用(或者指针)传递到另外一段逻辑(方法)里供这段逻辑适时调用。

你可能感兴趣的:(模板方法模式(Template Method Pattern))