}
Movie Rental::getMovie()
{
return _movie;
}
int Rental::getDaysRented()
{
return _daysRented;
}
double Rental::getCharge(int daysRented)
{
return _movie.getCharge(daysRented);
}
#include
#include "rental.h"
Rental::Rental(Movie movie, int daysRented)
{
qDebug()<<"construct Rental";
_movie = movie;
_daysRented = daysRented;
}
Movie Rental::getMovie()
{
return _movie;
}
int Rental::getDaysRented()
{
return _daysRented;
}
double Rental::getCharge(int daysRented)
{
return _movie.getCharge(daysRented);
}
main.cpp
[html]
#include
#include "movie.h"
#include "rental.h"
#include "regularprice.h"
#include "newreleaseprice.h"
#include "discountprice.h"
int main()
{
int daysRented = 30;
Movie movie("Book1",NEW_RELEASE);
Rental rental(movie,daysRented);
movie.setPriceCode(NEW_RELEASE, new NewReleasePrice);
rental.getCharge(daysRented);
return 0;
}
#include
#include "movie.h"
#include "rental.h"
#include "regularprice.h"
#include "newreleaseprice.h"
#include "discountprice.h"
int main()
{
int daysRented = 30;
Movie movie("Book1",NEW_RELEASE);
Rental rental(movie,daysRented);
movie.setPriceCode(NEW_RELEASE, new NewReleasePrice);
rental.getCharge(daysRented);
return 0;
}
【运行结果】
[html]
"construct Movie::Movie(Book1,1)"
construct Price
construct Movie::Movie()
construct Rental
construct Price
construct NewReleasePrice
NewReleasePrice::getCharge
"construct Movie::Movie(Book1,1)"
construct Price
construct Movie::Movie()
construct Rental
construct Price
construct NewReleasePrice
NewReleasePrice::getCharge
【结果分析】
[html]
movie.setPriceCode(NEW_RELEASE, new NewReleasePrice);
movie.setPriceCode(NEW_RELEASE, new NewReleasePrice);
传入priceCode和Price子对象作为参数,从运行结果可以看出,调用了NewReleasePrice的getCharge方法。
应用策略模式后,Rental::getCharge中仅有一行代码。
[html] view plaincopyprint double Rental::getCharge(int daysRented)
{
return _movie.getCharge(daysRented);
}
double Rental::getCharge(int daysRented)
{
return _movie.getCharge(daysRented);
}
将原来的getCharge做了搬移处理,而Movie::getCharge也很简短:
[html] view plaincopyprint double Movie::getCharge(int daysRented)
{
return _price->getCharge(daysRented);
}
double Movie::getCharge(int daysRented)
{
return _price->getCharge(daysRented);
}
*应用策略模式后,消除了switch-case语句,函数更为简洁。将Price单独抽出,成为一个类组,提高了代码的可重用性。
作者:tandesir