模板方法模式Template

模板方法模式Template/* * 功能:实现数组的排序和打印 * * 定义:在抽象类中定义一个算法(功能)的框架,将具体的步骤延迟到子类中实现。 * 组成:一个抽象类、一个或多个实现类 * 抽象类中包含: * 1.抽象方法,只定义规范,由子类来实现 * 2.模板方法,由父类实现,调用抽象方法来完成逻辑功能,一般定义为final方法,不允许子类重写 * * 优点: * 1.可扩展性,添加不同的实现类实现扩展 * 2.便于维护 * * 应用场合:多个子类拥有相同的方法,并且这些方法的逻辑功能相同时,建议使用模板方法模式 */Test03{/** 抽象方法,将数组按从大到小排序*/(int[] nums);/** 模板方法:打印排序后的数组*/public final void print(int[] nums){this.sort(nums);// 对数组进行排序System.out.println(“排序后的数组:”);for (int i = 0; i < nums.length; i++){System.out.print(nums[i] + ” “);}}}

测试类

/* * 测试类 */public class Test{(String[] args){int[] nums = { 12, 45, 2, 130, 43, 76, 3, 56 };Test03 test = new SubTest03();test.print(nums);}}

继承自Test03

/* * 继承自Test03 */{(int[] nums){for (int i = 0; i < nums.length – 1; i++){for (int j = 0; j < nums.length – 1 – i; j++){if (nums[j] < nums[j + 1]){int temp = nums[j];nums[j] = nums[j + 1];nums[j + 1] = temp;}}}}}模板方法实例/* * 使用模式方法模式,实现计算体积 */{main(String[] args){Volume v = new Cylinder(5.3, 4);System.out.println(“圆柱体的体积:” + v.getVolume());v = new Cuboid(5, 3.2, 6.4);System.out.println(“长方体的体积:” + v.getVolume());}}/* * 体积抽象类 */{Volume(double height){this.height = height;}public double getHeight(){return height;}getArea();getVolume(){return getArea() * height;}}/* * 圆柱体类Cylinder */ Volume{Cylinder(double height, double r){super(height);this.r = r;}// 重写父类的方法@Overridepublic double getArea(){return Math.PI * r * r;// 计算圆的面积}}/* * 长方体类Cuboid */ Volume{width;// 宽public Cuboid(double height, double length, double width){super(height);this.length = length;this.width = width;}// 重写父类的方法@Overridepublic double getArea(){return length * width;// 计算长方形的面积}}

,当你成功得意的时候,最重要的是瞧得起别人。

模板方法模式Template

相关文章:

你感兴趣的文章:

标签云: