码迷,mamicode.com
首页 > 其他好文 > 详细

模板方法

时间:2014-06-27 23:05:55      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:os      算法   c   一个   new   

模板方法定义: 定义一个算法框架,将算法框架的具体实现步骤放到子类去实现,从而达到可以多样化实现过程的目的.

抽象父类:‘

public abstract class AbstractClass {
protected abstract void doSomething1();
protected abstract void doSomething2();
protected abstract void doSomething3();
public final void doTheRealThing(){
this.doSomething1();
this.doSomething2();
this.doSomething3();
}
}

实现具体方法的子类:

public class ConcreteClass1 extends AbstractClass {

@Override
protected void doSomething1() {
// TODO Auto-generated method stub
System.out.println("I am the no.1 method in class 1");
}

@Override
protected void doSomething2() {
// TODO Auto-generated method stub
System.out.println("I am the no.2 method in class 1");
}

@Override
protected void doSomething3() {
// TODO Auto-generated method stub
System.out.println("I am the no.3 method in class 1");
}
}

public class ConcreteClass2 extends AbstractClass {

@Override
protected void doSomething1() {
// TODO Auto-generated method stub
System.out.println("I am the no.1 method in class 2");
}

@Override
protected void doSomething2() {
// TODO Auto-generated method stub
System.out.println("I am the no.2 method in class 2");
}

@Override
protected void doSomething3() {
// TODO Auto-generated method stub
System.out.println("I am the no.3 method in class 2");
}

}

调用方法:

public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractClass as = new ConcreteClass1();
as.doTheRealThing();

as = new ConcreteClass2();
as.doTheRealThing();
}

模板方法比较容易理解就是在抽象父类里定义了大的算法实现和算法实现具体小的方法的定义, 小方法的具体实现 放到继承他的子类里做.达到变化适应不同需求的目的.

 

模板方法,布布扣,bubuko.com

模板方法

标签:os      算法   c   一个   new   

原文地址:http://www.cnblogs.com/thinkqin/p/3811098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!