模式设计java代码_模板设计模式,简单Java代码实现

/**模板设计模式:定义一个算法的骨架,而将具体的算法延迟到子类中进行实现

* 优点:

* 使用模板方法模式,在定义算法骨架的同时,可以很灵活地实现具体的算法,满足用户灵活多变的需求

* 缺点:

* 如果算法骨架有修改的话,则需要修改抽象类。

*/

package july.star.template;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

/**

* GetTime

*

* @author MoXingJian

* @email 939697374@qq.com

* @date 2016年12月11日 下午5:35:40

* @version 1.0

*/

public abstract class GetTime {

public long getTime() {

long start = System.currentTimeMillis();

//以下这些方法都可以调用方法来嵌套进去使用

// 操作一

// for (int i = 0; i <= 10000; i++) {

// System.out.println(i);

// }

// 操作二

/*try {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.txt"));

byte[] bys = new byte[1024];

int len = 0;

while((len = bis.read(bys)) != -1){

bos.write(bys, 0, len);

bos.flush();

}

bos.close();

bis.close();

} catch (Exception e) {

e.printStackTrace();

}

*/

// 诸如此类的方法。。。。

code(); //用于存放以上的方法的代码

long end = System.currentTimeMillis();

return end - start;

}

//定义为抽象方法让子类来实现

public abstract void code() ;

}

//子类实现父类方法

package july.star.template;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

/**

* Code

*

* @author MoXingJian

* @email 939697374@qq.com

* @date 2016年12月11日 下午5:56:55

* @version 1.0

*/

public class Code extends GetTime {

// 将需要运行的代码放进其中

@Override

public void code() {

// 操作一

/*

* for (int i = 0; i <= 10000; i++) { System.out.println(i); }

*/

// 操作二

try {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.txt"));

byte[] bys = new byte[1024];

int len = 0;

while ((len = bis.read(bys)) != -1) {

bos.write(bys, 0, len);

bos.flush();

}

bos.close();

bis.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

//测试

package july.star.template;

/**

* GetTimeDemo

* 模板设计模式:定义一个算法的骨架,而将具体的算法延迟到子类中进行实现

* 优点:

* 使用模板方法模式,在定义算法骨架的同时,可以很灵活地实现具体的算法,满足用户灵活多变的需求

* 缺点:

* 如果算法骨架有修改的话,则需要修改抽象类。

* @author MoXingJian

* @email 939697374@qq.com

* @date 2016年12月11日 下午5:37:46

* @version 1.0

*/

public class GetTimeDemo {

public static void main(String[] args) {

//使用前

/*GetTime gt = new GetTime();

long time = gt.getTime();

System.out.println(time+"毫秒");*/

//使用模板设计模式后,就要新建一个类来将方法写进code()方法中

Code c = new Code();

long time = c.getTime();

System.out.println(time);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值