栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式——简单工厂模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式——简单工厂模式

大话设计模式 简单工厂模式
#include 
#include 

enum type{cashnormal, cashrebate, cashreturn};
typedef type CashType;

// 收费抽象类
class CashSuper
{
public:
    virtual double acceptCash(double money) = 0;
};

// 正常收费子类
class CashNormal : public CashSuper
{
public:
    inline double acceptCash(double money)
    {
        return money;
    }
};

// 打折收费子类
class CashRebate : public CashSuper
{
public:
    CashRebate() = default;
    CashRebate(double moneyRebate);
    inline double acceptCash(double money)
    {
        return moneyRebate_ * money;
    }

private:
    double moneyRebate_;
};

CashRebate::CashRebate(double moneyRebate):moneyRebate_(moneyRebate){}

// 返利收费子类
class CashReturn : public CashSuper
{
public:
    CashReturn() = default;
    CashReturn(double moneyCondition, double moneyReturn);
    double acceptCash(double money);

private:
    double moneyCondition_;
    double moneyReturn_;
};

CashReturn::CashReturn(double moneyCondition, double moneyReturn):moneyCondition_(moneyCondition), moneyReturn_(moneyReturn){}

double CashReturn::acceptCash(double money)
{
    double result = money;
    if (money > moneyCondition_)
    {
        result = money - floor(money/moneyCondition_)*moneyReturn_;
    }

    return result;
}

// 收费工厂类
class CashFactory
{
public:
    CashSuper* createCashAccept(CashType);
    ~CashFactory();
private:
    CashSuper* cashsuper_;
};

CashSuper* CashFactory::createCashAccept(CashType cashtype)
{
    switch (cashtype)
    {
        case cashnormal:
            cashsuper_ =  new CashNormal();
            break;
        case cashrebate:
            cashsuper_ =  new CashRebate(0.8);
            break;
        case cashreturn:
            cashsuper_ =  new CashReturn(300, 100);
            break;
        default:
            cashsuper_ =  nullptr;
    }

    return cashsuper_;
}

CashFactory::~CashFactory()
{
    if (cashsuper_ != nullptr)
    {
        delete cashsuper_;
        cashsuper_ = nullptr;
    }
}

int main()
{
    CashFactory cashfac;
    CashSuper* cashsuper = cashfac.createCashAccept(cashreturn);

    double totalprice = .0f;
    double unitprice = .0f;
    int num = 0;

    std::cout << "请输入商品单价: " << std::endl;
    std::cin >> unitprice;

    std::cout << "请输入商品数量: " << std::endl;
    std::cin >> num;

    totalprice = unitprice * num;

    totalprice =  cashsuper->acceptCash(totalprice);

    std::cout << "最终应付价格: " << totalprice << std::endl;

    delete cashsuper;

    return 0;
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/721340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号