模板模式13(17)

确定步骤,按步骤执行。

某一步骤未知其行为,另外定义。

刷牙、洗脸、吃早餐、坐公交、上班

刷牙、洗脸、吃早餐、坐地铁、上班

刷牙、洗脸、吃早餐、开   车、上班

坐公交、坐地铁和开车未知步骤。

执行步骤定义在模板中。

下列中Computer 是其模板:

package behavioral.template;

public abstract class Computer {


    final void install(){
        buyParts();
        packagePC();
        setup();
        use();
    }
    
    private void buyParts(){
        System.out.println("购买配件");
    }
    
    private void packagePC(){
        System.out.println("把配件组装成PC");
    }
    
    abstract void setup();
    
    private void use(){
        System.out.println("可以使用了");
    }
    
}
package behavioral.template;

public class SetupWindows extends Computer {

    @Override
    void setup() {

        System.out.println("安装windows系统");

    }

}

package behavioral.template;

public class SetupLinux extends Computer {

    @Override
    void setup() {

        System.out.println("安装linux系统");

    }

}

package behavioral.template;

public class Setup  extends Computer{

    @Override
    void setup() {
        
    }

}
package behavioral.template;

public class TemplateMain {

    public static void main(String[] args) {
        System.out.println("==自己安装==");
        Computer windowsPC = new SetupWindows();
        windowsPC.install();
        System.out.println("=====");
        Computer linuxPC = new SetupLinux();
        linuxPC.install();
        System.out.println("==给朋友组装好后,由朋友自己再选择安装什么系统==");
        Computer pc = new Setup();
        pc.install();
        
    }

}

 console:

==自己安装==
购买配件
把配件组装成PC
安装windows系统
可以使用了
=====
购买配件
把配件组装成PC
安装linux系统
可以使用了
==给朋友组装好后,由朋友自己再选择安装什么系统==
购买配件
把配件组装成PC
可以使用了
原文地址:https://www.cnblogs.com/zzlcome/p/11424649.html