类图
定义
- 定义一个操作中算法的骨架,而将这些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
优缺点
优点:
缺点:
适用环境:
- 子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
设计原则
-
好莱坞原则:别调用(打电话给)我们,我们会调用(打电话给)你。
-
好莱坞原则可以防止“依赖腐败”。当高层组件依赖底层组件,底层组件又依赖高层组件,高层组件又依赖边侧组件,边侧组件又依赖高层组件…,依赖腐败就发生了。在这种情况下,没有人可以轻易搞懂系统是如何设计的。
-
在好莱坞原则下,允许底层组件挂钩到系统上,但是高层组件会决定什么时候和怎样使用这些底层组件。即高层组件对底层组件的方式是:“别调用我们,我们会调用你”。
代码
CaffeineBeverage类:
#ifndef CADDEINEBEVERAGE_H
#define CADDEINEBEVERAGE_H
#include <QDebug>
class CaffeineBeverage
{
public:
void prepareRecipe();
virtual void brew() = 0;
virtual void addCondiments() = 0;
void boilWater();
void pourInCup();
virtual bool customerWantsCondiments();
};
#endif // CADDEINEBEVERAGE_H
#include "caffeinebeverage.h"
void CaffeineBeverage::prepareRecipe()
{
boilWater();
brew();
pourInCup();
addCondiments();
}
void CaffeineBeverage::boilWater()
{
qDebug() << "Boiling water";
}
void CaffeineBeverage::pourInCup()
{
qDebug() << "Pouring into cup";
}
bool CaffeineBeverage::customerWantsCondiments()
{
return true;
}
Coffee 类:
#ifndef COFFEE_H
#define COFFEE_H
#include "caffeinebeverage.h"
class Coffee : public CaffeineBeverage
{
public:
void brew() override;
void addCondiments() override;
bool customerWantsCondiments() override;
};
#endif // COFFEE_H
#include "coffee.h"
void Coffee::brew()
{
qDebug() << "Dripping Coffee through filter";
}
void Coffee::addCondiments()
{
qDebug() << "Adding Sugar and Milk";
}
bool Coffee::customerWantsCondiments()
{
}
Tea类:
#ifndef TEA_H
#define TEA_H
#include "caffeinebeverage.h"
class Tea : public CaffeineBeverage
{
public:
void brew() override;
void addCondiments() override;
};
#endif // TEA_H
#include "tea.h"
void Tea::brew()
{
qDebug() << "Steeping the Tea";
}
void Tea::addCondiments()
{
qDebug() << "Adding Lemon";
}
测试:
#include "mainwindow.h"
#include "tea.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
Tea *myTea = new Tea();
myTea->prepareRecipe();
}
MainWindow::~MainWindow()
{
}