zoukankan      html  css  js  c++  java
  • 模板方法模式

    模板方式模式(TemplateMethod):定义一个操作中的骨架算法,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

    当我们要完成在某一细节层次一致的一个过程或一系列步骤,但其个别步骤在更详细的层次上的实现可能不同时,我们通常考虑用模板方法模式来处理。

    模板方法模式是通过把不变行为搬移到父类,去除子类中的重复代码。

    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();
        }
    
    }
  • 相关阅读:
    《吊打面试官》系列-缓存雪崩、击穿、穿透
    WebGL学习之纹理贴图
    小试小程序云开发
    关于socket.io的使用
    动画函数的绘制及自定义动画函数
    canvas实现俄罗斯方块
    Redis集群
    手工搭建基于ABP的框架
    手工搭建基于ABP的框架(3)
    手工搭建基于ABP的框架(2)
  • 原文地址:https://www.cnblogs.com/ccgjava/p/7062976.html
Copyright © 2011-2022 走看看