This commit is contained in:
Alexander Zhirov 2021-10-18 02:32:50 +03:00
parent 3b15979dfe
commit 14ba9da607
4 changed files with 207 additions and 0 deletions

92
lesson_1/src/duck.hpp Normal file
View File

@ -0,0 +1,92 @@
/*
* duck.hpp
*
* Created on: 18 окт. 2021 г.
* Author: alexander
*/
#pragma once
#include <iostream>
class Duck
{
protected:
FlyBehavior *flyBehavior;
QuackBehavior *quackBehavior;
public:
void performQuack()
{
quackBehavior->quack();
}
void performFly()
{
flyBehavior->fly();
}
void swim()
{
std::cout << "All ducks float, even decoys!" << std::endl;
}
virtual void display() { }
void setFlyBehavior(FlyBehavior *fb)
{
if (flyBehavior)
{
delete flyBehavior;
}
flyBehavior = fb;
}
void setQuackBehavior(QuackBehavior *qb)
{
if (quackBehavior)
{
delete quackBehavior;
}
quackBehavior = qb;
}
virtual ~Duck()
{
if (flyBehavior)
{
delete flyBehavior;
}
if (quackBehavior)
{
delete quackBehavior;
}
}
};
class MallardDuck : public Duck
{
public:
MallardDuck()
{
quackBehavior = new Quack;
flyBehavior = new FlyWithWings;
}
};
class ModelDuck : public Duck
{
public:
ModelDuck()
{
flyBehavior = new FlyNoWay;
quackBehavior = new Quack;
}
void display()
{
std::cout << "I'm a model duck" << std::endl;
}
};

View File

@ -0,0 +1,44 @@
/*
* fly_behavior.hpp
*
* Created on: 18 окт. 2021 г.
* Author: alexander
*/
#pragma once
#include <iostream>
class FlyBehavior
{
public:
virtual void fly() = 0;
virtual ~FlyBehavior() { }
};
class FlyWithWings : public FlyBehavior
{
public:
void fly()
{
std::cout << "I'm flying!" << std::endl;
}
};
class FlyNoWay : public FlyBehavior
{
public:
void fly()
{
std::cout << "I can't fly" << std::endl;
}
};
class FlyRocketPowered : public FlyBehavior
{
public:
void fly()
{
std::cout << "I'm flying with a rocket!" << std::endl;
}
};

27
lesson_1/src/main.cpp Normal file
View File

@ -0,0 +1,27 @@
/*
* main.cpp
*
* Created on: 18 окт. 2021 г.
* Author: alexander
*/
#include "fly_behavior.hpp"
#include "quack_behavior.hpp"
#include "duck.hpp"
int main()
{
Duck *mallard = new MallardDuck;
mallard->performQuack();
mallard->performFly();
Duck *model = new ModelDuck;
model->performFly();
model->setFlyBehavior(new FlyRocketPowered);
model->performFly();
delete mallard;
delete model;
return 0;
}

View File

@ -0,0 +1,44 @@
/*
* quack_behavior.hpp
*
* Created on: 18 окт. 2021 г.
* Author: alexander
*/
#pragma once
#include <iostream>
class QuackBehavior
{
public:
virtual void quack() = 0;
virtual ~QuackBehavior() { }
};
class Quack : public QuackBehavior
{
public:
void quack()
{
std::cout << "Quack" << std::endl;
}
};
class Squeak : public QuackBehavior
{
public:
void quack()
{
std::cout << "Squeak" << std::endl;
}
};
class MuteQuack : public QuackBehavior
{
public:
void quack()
{
std::cout << "<< Silence >>" << std::endl;
}
};