光輝歲月

导航

 

  第一次好好的看设计模式,可能有不对的地方,大佬们可以下面指出,感谢!

  ----------- 分割线 ----------

 

  考题抄错会做也白搭——模板方法模式

 

uml图:

代码中可能用到的地方:

1、很多类存在许多耦合,可以抽取模板父类

2、业务存在耦合,可以进行抽取模板,不考虑业务实现,但是业务结果是一致的

现在的电脑组装,也是个模板方法模式呢,电脑主要由主板、硬盘、处理器、显卡、显示屏、组成;

定义一个电脑类:

public abstract class Computer {

    public String board;//主板

    public String caliche;//硬盘

    public String cpu;//处理器

    public String graphicsCard;//显卡

    public String display;//显示屏

    public abstract void board();

    public abstract void caliche();

    public abstract void cpu();

    public abstract void graphicsCard();

    public abstract void display();

    public void assemble(){
        board();
        caliche();
        cpu();
        graphicsCard();
        display();
        System.out.println("组装电脑成功,电脑主板是:"+board+",硬盘是:"+caliche+",处理器是:"+cpu+",显卡是:"+
                graphicsCard+",显示屏是;"+display);
        System.out.println(JSON.toJSONString(this));
    }

}

三星电脑实现类:

public class Samsung extends Computer {
    @Override
    public void board() {
        this.board = "三星主板";
        System.out.println("组装上了"+board);
    }

    @Override
    public void caliche() {
        this.caliche = "256GB的SSD硬盘";
        System.out.println("组装上了"+caliche);
    }

    @Override
    public void cpu() {
        this.cpu = "i7-8565U";
        System.out.println("组装上了"+cpu);
    }

    @Override
    public void graphicsCard() {
        this.graphicsCard = "独立显卡4GB";
        System.out.println("组装上了"+graphicsCard);
    }

    @Override
    public void display() {
        this.display = "13.3英寸显示屏";
        System.out.println("组装上了"+display);
    }
}

戴尔电脑实现类:

public class Dell extends Computer {
    @Override
    public void board() {
        this.board = "戴尔主板";
        System.out.println("组装上了"+board);
    }

    @Override
    public void caliche() {
        this.caliche = "512GB的SSD硬盘";
        System.out.println("组装上了"+caliche);
    }

    @Override
    public void cpu() {
        this.cpu = "i7-8550U";
        System.out.println("组装上了"+cpu);
    }

    @Override
    public void graphicsCard() {
        this.graphicsCard = "GTX1050";
        System.out.println("组装上了"+graphicsCard);
    }

    @Override
    public void display() {
        this.display = "15.6英寸显示屏";
        System.out.println("组装上了"+display);
    }
}

程序调用:

public class Main {

    public static void main(String[] args) throws CloneNotSupportedException {
        Computer samsung = new Samsung();
        samsung.assemble();
        System.out.println("---------分割线-----------");
        Computer dell = new Dell();
        dell.assemble();
    }

}

结果:

定义好了电脑模板,接下来去实现电脑模板就能组装出各种电脑了,这就是模板方法模式。

定义模板,但是不是由自己实现,谁需要产品实现模板,做出产品;代码、业务解耦。

posted on 2019-07-01 15:16  光輝歲月  阅读(198)  评论(1编辑  收藏  举报