基于c++的策略模式初探。

本文介绍了一种基于抽象类的计费模式设计方法,通过定义抽象基类AbsAccount及派生类HalfAccount和PromoteAccount实现不同的计费策略。HalfAccount提供五折优惠,而PromoteAccount则针对超过100元的部分减免60元。此外,还提供了一个工厂类AccountFactory用于创建不同类型的计费对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



#ifndef ABSACCOUNT_H
#define ABSACCOUNT_H
class AbsAccount {
public:
    virtual double getTotalPrice(double unitPrice,int counts)=0;
    virtual ~AbsAccount(){

    }//need define when declare.


};


#endif // ABSACCOUNT_H



#ifndef HALFACCOUNT_H
#define HALFACCOUNT_H
#include "AbsAccount.h"
class HalfAccount : public AbsAccount{
public:
    HalfAccount();


 virtual double getTotalPrice(double unitPrice,int counts);

 ~HalfAccount(){
 }

};
#endif // HALFACCOUNT_H



#include "HalfAccount.h"
double HalfAccount::getTotalPrice(double unitPrice,int counts){
return unitPrice*0.5*counts;

}


HalfAccount::HalfAccount():AbsAccount(){

}



#ifndef PROMOTEACCOUNT_H
#define PROMOTEACCOUNT_H
#include "AbsAccount.h"
class PromoteAccount : public AbsAccount{
public:
    PromoteAccount();


 virtual double getTotalPrice(double unitPrice,int counts);

 ~PromoteAccount(){
 }

};



#endif // PROMOTEACCOUNT_H



#include "PromoteAccount.h"
double PromoteAccount::getTotalPrice(double unitPrice,int counts){
double d= unitPrice*counts;

if(d>100)
    d=d-60;
return d;
}


PromoteAccount::PromoteAccount():AbsAccount(){

}




#ifndef ACCOUNTFACTORY_H
#define ACCOUNTFACTORY_H
#include "AbsAccount.h"
class AccountFactory{
public:
    static AbsAccount* createAccount(int type_id);

static const int TYPE_HALF_ACCOUNT=1;
static const int TYPE_PROMOTE_ACCOUNT=2;

};


#endif // ACCOUNTFACTORY_H



#include "AccountFactory.h"
#include "HalfAccount.h"
#include "PromoteAccount.h"
AbsAccount* AccountFactory::createAccount(int type_id){
    switch(type_id){
    case TYPE_HALF_ACCOUNT:
        return new HalfAccount;
    case TYPE_PROMOTE_ACCOUNT:
        return new PromoteAccount;
    default:
        return 0;


    }


}


#include "AccountFactory.h"
#include <iostream>
using namespace std;
int main(){
    double total1,total2;
    AbsAccount* promoteimpl=0;
    AbsAccount* halfimpl=0;

    halfimpl=AccountFactory::createAccount(AccountFactory::TYPE_HALF_ACCOUNT);
    if(!halfimpl)
        goto exit;
 total1=halfimpl->getTotalPrice(10,10);

cout<<"total1:"<<total1<<endl;

delete halfimpl;
promoteimpl=AccountFactory::createAccount(AccountFactory::TYPE_PROMOTE_ACCOUNT);
if(!promoteimpl)
    goto exit;
 total2=promoteimpl->getTotalPrice(10,10);
cout<<"total2:"<<total2<<endl;
delete promoteimpl;
exit:
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值