Construction template pattern usage example of Java abstract class
This article describes the construction template pattern usage of Java abstract classes. Share with you for your reference, as follows:
A finishing touch
Some simple rules for template patterns.
The abstract parent class can only define some methods that need to be used, and the parts that cannot be implemented can be abstracted into abstract methods and left to the subclass for implementation.
The parent class may contain methods that need to call other series of methods. These called methods can be implemented by the parent class or its subclasses. The method provided in the parent class only defines a general algorithm. Its implementation may not be completely implemented by itself, but must rely on the assistance of the subclass of the generator.
II. Actual combat
1 parent class
public abstract class SpeedMeter { // 转速 private double turnRate; public SpeedMeter() { } // 把返回车轮的半径的方法定义为抽象方法 public abstract double geTradius(); public void setTurnRate(double turnRate) { this.turnRate = turnRate; } // 计算速度的通用算法 public double getSpeed() { // 速度等于 车轮半径 * 2 * PI * 转速 return Math.PI * 2 * geTradius() * turnRate; } }
Subclass 2
public class CarSpeedMeter extends SpeedMeter { public double geTradius() { return 0.28; } public static void main(String[] args) { CarSpeedMeter csm = new CarSpeedMeter(); csm.setTurnRate(15); System.out.println(csm.getSpeed()); } }
Three operation
For more Java related content, interested readers can view the special topics of this site: introduction and advanced tutorial of java object-oriented programming, tutorial of Java data structure and algorithm, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills
I hope this article will be helpful to you in Java programming.