Reflect java abstract class - template pattern

A plurality of abstract class is a concrete subclass of abstract superclass, with a high level of abstraction; abstract class as the template to the subclass design avoids arbitrary subclass;

 

Mainly reflects the abstract class template pattern design, abstract classes as a universal template multiple sub-classes, subclasses to expand on the basis of an abstract class, but an abstract class subclass generally reserved behavior in general;

To write an abstract parent class, the parent provides a common method for multiple subclasses, and put one or more abstract methods left to the subclass to achieve, this is the template design pattern;

 

Template model is simple rule applies:

1. abstract parent class can define only some of the processes require the use of the remaining leaving subclasses to achieve;

2. The method defined parent class provides only a general algorithm, its implementation must rely on an auxiliary subclass;

 

My summary:

If the parent class method did not want to quilt class override, you can add the final in front of the modified keyword.

 

Eg:

package reviewDemo;

// template pattern

 

// abstract class contains a lot of abstract methods, subclass must override go!

abstract class Method{

    abstract Double MUL (); // return type is void if, then, the following error, because there is no return value, not reference!

    abstract double divid();

    void show(){

        . The System OUT .println ( "Area is:" + mul ()); // perimeter

        . The System OUT .println ( "Area is:" + divid ()); // area

    }

}

 

class Square extends Method{

    double d;

   

    public Square(double d) {

        super();

        this.d = d;

    }

 

    @Override

    double mul() {

        return d * d;

    }

 

    @Override

    double divid() {

        return 4 * d;

    }

}

 

class Cirle extends Method{

    double r;

   

    public Cirle(double r) {

        super();

        this.r = r;

    }

 

    @Override

    double mul() {

        return 2 * 3.14 * r;

    }

 

    @Override

    double divid() {

        return 3.14 * r * r;

    }

}

 

public class Demo16 {

    public static void main(String[] args) {

        Square s = new Square(5);

        s.show();

        Cirle c = new Cirle(4);

        c.show();

    }

}

Guess you like

Origin www.cnblogs.com/fanweisheng/p/11131568.html