// Desinger.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <list>
using std::cout;
using std::list;
using std::string;
//开闭原则
class IBook {
public:
//获取书名
virtual string GetName() {return "";}
//书售价
virtual int GetPrice() {return 0;}
//作者
virtual string GetAuthor() {return "";}
};
class NoveBook : public IBook {
private:
string m_strName;
int m_nPrice;
string m_strAuthor;
public:
NoveBook(string _name, int _price, string _author)
: m_strName(_name)
, m_nPrice(_price)
, m_strAuthor(_author)
{}
virtual string GetAuthor() {
return m_strAuthor;
}
virtual string GetName() {
return m_strName;
}
virtual int GetPrice() {
return m_nPrice;
}
};
//然后作者要添加一个降价书本的模块
class OffNovelBook : public NoveBook {
public:
OffNovelBook(string _name, int _price, string _author)
: NoveBook(_name, _price, _author) {
}
virtual int GetPrice() {
int selfprice = static_cast<NoveBook>(*this).GetPrice();
int offPrice = 0;
if (selfprice > 4000) {
offPrice = selfprice*90/100;
} else {
offPrice = selfprice*80/100;
}
return offPrice;
}
};
//作者代码有没写,我就自己写了
class BookStore {
private:
static list<IBook*> m_booklist;
static void Store();
public:
static void main();
};
list<IBook*> BookStore::m_booklist;
void BookStore::Store() {
m_booklist.push_back(new OffNovelBook("天龙八部", 3200, "金庸"));
m_booklist.push_back(new OffNovelBook("巴黎圣母院", 5600, "雨果"));
m_booklist.push_back(new OffNovelBook("悲惨世界", 4300, "雨果"));
}
void BookStore::main() {
Store();
for (list<IBook*>::iterator i = m_booklist.begin();
i != m_booklist.end(); i++) {
cout << (*i)->GetName() << ":"
<< (*i)->GetAuthor() << ":"
<< (*i)->GetPrice();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
BookStore::main();
system("pause");
return 0;
}
设计模式观后(c++还原之四 开闭原则 )
最新推荐文章于 2021-12-01 09:38:40 发布