模板模式:通过抽象类来定义一个逻辑模板,逻辑框架,逻辑原型,然后将无法决定的部分抽象成抽象类交由子类来实现,一般这些抽象类的调用逻辑还在抽象类中完成。这么看来,模板就是定义一个框架,比如盖房子,我们定义一个模板,房子要封闭,有门,有窗等等,但是要什么样的门,什么样的窗,这些并不在描述,这个交由子类来完善。
/*** 房子模板*/public abstract class HouseTemplate {protected String name;protected HouseTemplate (String name) {this.name = name;}protected abstract void buildDoor();protected abstract void buildWindow();protected abstract void buildWall();protected abstract void buildBase();/*** 公共逻辑*/public final void buildHouse() {buildBase();buildWall();buildWindow();buildDoor();}}
public class Clienter {public static void main(String[] args) {HouseTemplate houseOne = new HouseOne("房子1");HouseTemplate houseTwo = new HouseTwo("房子2");houseOne.buildHouse();houseTwo.buildHouse();}}
/*** 房子1*/public class HouseOne extends HouseTemplate {protected HouseOne(String name) {super(name);}@Overrideprotected void buildDoor() {System.out.println(name + "采用防盗门");}@Overrideprotected void buildWindow() {System.out.println(name + "窗户向北");}@Overrideprotected void buildWall() {System.out.println(name + "墙使用大理石");}@Overrideprotected void buildBase() {System.out.println(name + "地址使用钢铁");}}
/*** 房子2*/public class HouseTwo extends HouseTemplate {protected HouseTwo(String name) {super(name);}@Overrideprotected void buildDoor() {System.out.println(name + "采用木门");}@Overrideprotected void buildWindow() {System.out.println(name + "窗户向南");}@Overrideprotected void buildWall() {System.out.println(name + "墙体玻璃");}@Overrideprotected void buildBase() {System.out.println(name + "地基花岗岩");}}
