23种设计模式----模板方法模式

模板方法模式

1.来个抽象的模板方法run

public abstract class AbstractMethod {
    abstract void start();

    abstract void stop();

    public void run() {
        this.start();
        this.stop();
    }
}

2.具体实现模板里面的方法

public class TemplateMethod extends AbstractMethod {
    private static final String TAG = "TemplateMethod";
    @Override
    void start() {
        Log.e(TAG, "start: " );
    }

    @Override
    void stop() {
        Log.e(TAG, "stop: " );
    }
}

3.测试类 

public class Test {
    public void test() {
        TemplateMethod templateMethod = new TemplateMethod();
        templateMethod.run();
    }
}

---------------------------------------------------------------------------------------------------------------------------------------------------------

例子2

public abstract class Paper {
    private static final String TAG = "Paper";
    public void subjectOne(){
        Log.e(TAG, "subject: 题目: 什么姿势睡眠质量好!");
        Log.e(TAG, "subject: A:躺着  B:站着  C:倒着");
        Log.e(TAG, "subject: 选择: "+ answerOne() );

    }
    public void subjectTwo(){
        Log.e(TAG, "subject: 题目: 喜欢什么运动!");
        Log.e(TAG, "subject: A:躺着  B:站着  C:倒着");
        Log.e(TAG, "subject: 选择: "+ answerTwo() );

    }
    public void Play(){
        Log.e(TAG, "Play: " );
        subjectOne();
        subjectTwo();
    }
    protected abstract String answerOne();
    protected abstract String answerTwo();
}
public class StudentA extends Paper {
    @Override
    protected String answerOne() {
        return "A";
    }

    @Override
    protected String answerTwo() {
        return "B";
    }
}
public class Test {
    public void test() {
        StudentA studentA = new StudentA();
        studentA.Play();
    }
}

 

你可能感兴趣的:(23种设计模式)