每日总结
软件设计模式 享元模式:
#include<iostream>
#include<string>
using namespace std;
class AbstractText {
public:
virtual string getType() = 0;
virtual void use() = 0;
};
class TextFactory {
public:
int totalwhite = 0;
int totalblack = 0;
int totalword = 0;
AbstractText* getText(string type);
int getTotalWhite();
int getTotalBlack();
int getTotalWord();
};
class Word :public AbstractText{
public:
string getType();
void use();
};
class White :public AbstractText{
public:
string getType();
void use();
};
class Black:public AbstractText{
public:
string getType();
void use();
};
string White::getType(){
return "white";
}
void White::use() {
cout << "白棋\n";
}
string Black::getType() {
return "black";
}
void Black::use() {
cout << "黑棋\n";
}
string Word::getType() {
return "Hello world";
}
void Word::use() {
cout << "下棋\n";
}
AbstractText* TextFactory::getText(string type) {
if (type=="white") {
totalwhite++;
AbstractText* a = new White();
return a;
}
else if (type=="black") {
totalblack++;
AbstractText* a = new Black();
return a;
}
else if (type=="word") {
totalword++;
AbstractText *a = new Word();
return a;
}
else
return NULL;
}
int TextFactory::getTotalWhite() {
return totalwhite;
}
int TextFactory::getTotalBlack() {
return totalblack;
}
int TextFactory::getTotalWord() {
return totalword;
}
int main() {
AbstractText *at1, *at2, *at3, *at4;
TextFactory *tf = new TextFactory();
at3 = tf->getText("word");
at1 = tf->getText("white");
at1->use();
at3->use();
at2 = tf->getText("black");
at2->use();
at3->use();
at4 = tf->getText("white");
at4->use();
at3->use();
cout << "white: " << tf->getTotalWhite() << endl;
cout << "black: " << tf->getTotalBlack() << endl;
cout << "word: " << tf->getTotalWord() << endl;
return 0;
}