标签:ring blog extend rri print auth rac ati size
模板模式:定义一个操作中的骨架算法,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
TestPager.java类
package template; /** * 把不变的行为搬到父类,去除子类重复的代码 * @author 煞笔 * */ public abstract class TestPager { public void testQuestion1(){ System.out.println("1+2="+answer1()); } public void testQuestion2(){ System.out.println("3+2="+answer2()); } public void testQuestion3(){ System.out.println("5+2="+answer3()); } public abstract int answer1(); public abstract int answer2(); public abstract int answer3(); }
TestPagerA.java类
package template; public class TestPagerA extends TestPager { @Override public int answer1() { return 3; } @Override public int answer2() { return 5; } @Override public int answer3() { return 7; } }
TestPagerB.java类
package template; public class TestPagerB extends TestPager { @Override public int answer1() { return 3; } @Override public int answer2() { return 5; } @Override public int answer3() { return 6; } }
Business.java类
package template; public class Business { public static void main(String[] args) { TestPager tp = new TestPagerA(); tp.testQuestion1(); tp.testQuestion2(); tp.testQuestion3(); tp = new TestPagerB(); tp.testQuestion1(); tp.testQuestion2(); tp.testQuestion3(); } }
标签:ring blog extend rri print auth rac ati size
原文地址:http://www.cnblogs.com/ccgjava/p/7062976.html