code refactoring: fix memory leaks, code style, etc.

This commit is contained in:
Jakub Vojvoda
2019-01-31 19:57:40 +01:00
parent a8681552c4
commit a0b0ea4f8e
24 changed files with 960 additions and 566 deletions

View File

@@ -14,9 +14,12 @@
* Prototype
* declares an interface for cloning itself
*/
class Prototype {
class Prototype
{
public:
virtual Prototype *clone() = 0;
virtual ~Prototype() {}
virtual Prototype* clone() = 0;
virtual std::string type() = 0;
// ...
};
@@ -25,23 +28,33 @@ public:
* Concrete Prototype A and B
* implement an operation for cloning itself
*/
class ConcretePrototypeA : public Prototype {
class ConcretePrototypeA : public Prototype
{
public:
Prototype *clone() {
return new ConcretePrototypeA;
~ConcretePrototypeA() {}
Prototype* clone()
{
return new ConcretePrototypeA();
}
std::string type() {
std::string type()
{
return "type A";
}
// ...
};
class ConcretePrototypeB : public Prototype {
class ConcretePrototypeB : public Prototype
{
public:
Prototype *clone() {
return new ConcretePrototypeB;
~ConcretePrototypeB() {}
Prototype* clone()
{
return new ConcretePrototypeB();
}
std::string type() {
std::string type()
{
return "type B";
}
// ...
@@ -51,34 +64,52 @@ public:
* Client
* creates a new object by asking a prototype to clone itself
*/
class Client {
class Client
{
public:
static Prototype* make(int index) {
return types[index]->clone();
static void init()
{
types[ 0 ] = new ConcretePrototypeA();
types[ 1 ] = new ConcretePrototypeB();
}
static void remove()
{
delete types[ 0 ];
delete types[ 1 ];
}
static Prototype* make( const int index )
{
if ( index >= n_types )
{
return nullptr;
}
return types[ index ]->clone();
}
// ...
private:
static Prototype* types[2];
};
Prototype* Client::types[] =
{
new ConcretePrototypeA,
new ConcretePrototypeB
// ...
static Prototype* types[ 2 ];
static int n_types;
};
Prototype* Client::types[ 2 ];
int Client::n_types = 2;
int main()
{
Prototype* prototype;
prototype = Client::make(0);
std::cout << "Prototype: " << prototype->type() << std::endl;
prototype = Client::make(1);
std::cout << "Prototype: " << prototype->type() << std::endl;
Client::init();
Prototype *prototype1 = Client::make( 0 );
std::cout << "Prototype: " << prototype1->type() << std::endl;
delete prototype1;
Prototype *prototype2 = Client::make( 1 );
std::cout << "Prototype: " << prototype2->type() << std::endl;
delete prototype2;
Client::remove();
return 0;
}