zoukankan      html  css  js  c++  java
  • Java抽象类应用—模板方法模式

    模板方法模式(Templete method)

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

    例:

     1 package practice1;
     2 
     3 import java.util.Random;
     4 
     5 public class Test8 {
     6      public static void main(String []args){
     7          Games g=new Girl();
     8          g.play();
     9      }
    10 }
    11 abstract class Games{
    12   public void play(){//定义一个操作中的算法骨架
    13       System.out.println("准备");
    14       System.out.println("开始");
    15       if(result()){
    16           System.out.println("赢了");
    17       }else{
    18           System.out.println("输了");
    19       }
    20   }
    21   
    22   public abstract  boolean result();//将一些可变部分的实现延迟到子类中
    23 }
    24 
    25 class Girl extends Games{
    26 
    27     @Override
    28     public boolean result() {
    29         Random r=new Random();
    30         return r.nextBoolean();
    31     }
    32     
    33 }
    34 class ModeGirl extends Games{
    35 
    36     @Override
    37     public boolean result() {
    38         return false;
    39     }
    40     
    41 }
  • 相关阅读:
    微软Silverlight 2.0 最新版本GDR发布
    POJ 2635, The Embarrassed Cryptographer
    POJ 3122, Pie
    POJ 1942, Paths on a Grid
    POJ 1019, Number Sequence
    POJ 3258, River Hopscotch
    POJ 3292, Semiprime Hnumbers
    POJ 2115, C Looooops
    POJ 1905, Expanding Rods
    POJ 3273, Monthly Expense
  • 原文地址:https://www.cnblogs.com/chenxing818/p/4681832.html
Copyright © 2011-2022 走看看