java模式:模板模式的简单理解

本文介绍模板模式的概念,并通过一个生动的例子来展示如何使用该模式。具体来说,文章讲解了如何利用模板模式处理不同对象放入冰箱的过程,其中包括了共同的操作步骤以及特定于对象的操作。

1.模板模式就是用虚类作为基类将几个要执行差不多操作中相同的部分提取出来,不同的部分各自实现!

2.下面给出简单栗子:

  我要进行的操作是将大象和狐狸放入冰箱,放入大象和狐狸有相同的步骤:开冰箱和关冰箱,这个操作在基类中实现就好,而不同的在于具体操作部分:

    一,大象太胖了,要测量并切片才能放入冰箱

    二,狐狸太臭了,要洗干净并擦干

所以程序如下:

1.基类:BasicFridgeOperation.java

package com.learn.templateMode;

/**
 * Created by garfield on 9/15/2016.
 */
public abstract class BasicFridgeOperation {

    private void openFridge(){
        System.out.println("open the fridge door");
    }


    /**
     * different parts about one of the whole steps
     * the subclass will make different implements
     */
    protected abstract void operateFridge();

    private void closeFridge(){
        System.out.println("close the fridge door");
    }

    /**
     * the same operation steps
     */
    public void operation(){
        openFridge();
        operateFridge();
        closeFridge();
    }

}

2,放入大象类:OperateElephant.java

package com.learn.templateMode;

/**
 * Created by garfield on 9/15/2016.
 */
public class OperateElephant extends BasicFridgeOperation {
    /**
     * same function but different implement
     */
    protected void operateFridge() {
        System.out.println("measure the elephant");
        System.out.println("slice up the elephant");
        System.out.println("put the elephant in");
    }

}

3,放入狐狸类:OperateFox.java

package com.learn.templateMode;

/**
 * Created by garfield on 9/15/2016.
 */
public class OperateFox extends BasicFridgeOperation {
    /**
     * same function but different implement
     */
    protected void operateFridge() {
        System.out.println("clean up the fox");
        System.out.println("dry the fox");
        System.out.println("put the fox in");
    }
}

4,测试:OperationTest.java

package com.learn.templateMode;

/**
 * Created by garfield on 9/15/2016.
 */
public class OperationTest {
    public static void main(String[] args) {
        System.out.println("====== begin to deal with the elephant=========");
        BasicFridgeOperation basicFridgeOperation = new OperateElephant();
        basicFridgeOperation.operation();
        System.out.println("====== begin to deal with the fox=========");
        BasicFridgeOperation basicFridgeOperation2 = new OperateFox();
        basicFridgeOperation2.operation();
    }
}

5,输出结果:

====== begin to deal with the elephant=========
open the fridge door
measure the elephant
slice up the elephant
put in the elephant
close the fridge door
====== begin to deal with the fox=========
open the fridge door
clean up the fox
dry the fox
put in the fox
close the fridge door

,that,s all.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值