您的位置:首页 > 编程语言 > Java开发

JAVA中的设计模式 - 模版方法模式

2017-12-14 12:02 302 查看

JAVA中的设计模式 - 模版方法模式

模版方法模式:通过调用抽象父类,实现对子类的调用

1.构建抽象类

import java.util.Random;

/**
* Created by 谭健 on 2017/12/14. 11:45.
* © All Rights Reserved.
*/
public abstract class AbstractParent {

public final int birthToChild(int bound) {
System.out.println("调用了抽象类自己的 birthToChild() 方法。");
int number = new Random().nextInt(bound);
return birthToChild(correct(number),number);
}

public abstract int birthToChild(boolean isDie,int number);

public boolean correct(int number) {
System.out.println("调用了抽象类自己的 correct() 方法。");
return number == 0;
}
}


2.构建子类

/**
* Created by 谭健 on 2017/12/14. 11:53.
* © All Rights Reserved.
*/
public class RealChild extends AbstractParent {

@Override
public int birthToChild(boolean isDie, int number) {
System.out.println("调用了抽象类子类的 birthToChild() 方法。");
return
4000
isDie ? 0 : number;
}

public static void main(String[] args) {
AbstractParent parent = new RealChild();
parent.birthToChild(2);
}
}


3.输出

调用了抽象类自己的 birthToChild() 方法。
调用了抽象类自己的 correct() 方法。
调用了抽象类子类的 birthToChild() 方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: