TemplateMethod

模版方法模式

例:

父类

package extendsTest;

public abstract class Father {
	abstract void say();

	public void tm() {
		say();
	}

}

 子类1:

package extendsTest;

public class Son1 extends Father {
	@Override
	void say() {
		System.out.println("a");
	}

}

 子类2:

package extendsTest;

public class Son2 extends Father {

	@Override
	void say() {
		System.out.println("b");
	}

}

 测试类

package extendsTest;

import junit.framework.TestCase;

public class TemplateMethod extends TestCase {
	public void testMySay() {
		Father tFather = new Son1();
		tFather.tm();
		Father tFather2 = new Son2();
		tFather2.tm();
	}

}

 在测试类中 fFather 可以直接调用say()方法 执行结果是一样的

a
b

 因为子类1 和子类2 没有同样的代码 如果有这种写法就是好的 可以把同样的代码写进去 实现了提炼重复代码和模版方法模式

posted on 2013-04-08 16:41  _飘逸的腿毛  阅读(145)  评论(0)    收藏  举报

导航