java基础——抽象类及模板方法设计模式

抽象类及创建匿名子类对象

package abstracttest;

/*
 *     抽象类的匿名子类
 * 
 * */

abstract class Person {
    String name;
    int age;
    
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Person() {
        super();
    }
    
    public abstract void eat();
    
    public void walk() {
        System.out.println("人走路");
    }
}
class Student extends Person{
    int score;
    
    
    public Student() {
        super();
    }
    public Student(String name, int age) {
        super(name, age);
    }
    public Student(String name, int age, int score) {
        super(name, age);
        this.score = score;
    }

    public void eat() {
        System.out.println("student eat");
    }
}

public class AbstractTest {
    public static void main(String[] args) {
        
        // p创建一个匿名子类的对象,对象的名字叫p,对象内把要重写的抽象方法实现了
        Person p = new Person() {
            
            @Override
            public void eat() {
                System.out.println("1");
            }
        };
        method(p);
        
    }
    public static void method(Person p) {
        p.eat();
        p.walk();
    }
}

模板方法设计模式:模板方法是个抽象类,里面的模板方法先把通用部分写好,然后声明一个钩子方法,让子类去实现,new的子类对象调用模板方法时,就会自动调用钩子方法了

package TemplateMethod;

import java.util.ArrayList;

/*
 * 
 *     抽象类应用:模板方法的设计模式
 *         概念:钩子方法,像一个钩子,抽象类下面挂哪个子类对象,就调用那个子类实现的钩子方法
 * 
 * */

public class TemplateTest {
    public static void main(String[] args) {
        SubTemplate t = new SubTemplate();
        
        t.spendTime();
    }
    
    
}

abstract class Template{
    
    //计算某段代码执行所需花费的时间
    public void spendTime() {
        
        long start = System.currentTimeMillis();
        
        this.code();    //不确定的部分
        
        long end = System.currentTimeMillis();
    
        System.out.println("花费时间为" + (end-start));
    }
    
    public abstract void code();
    
}

class SubTemplate extends Template{
    
    @Override
    public void code() {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        for(int i=2;i<=100000;i++)
            arrayList.add(i);
        System.out.println(arrayList.size());
            
    }
    
}

猜你喜欢

转载自www.cnblogs.com/zsben991126/p/12148118.html