Dzień dobry, po kursie na udemy "C# Intermediate: Classes, Interfaces and OOP" napisałem na szybko przykład użycia kompozycji.
Czy to jest prawidłowo wykonane?
Jeżeli nie, które elementy należy poprawić, aby było to prawidłowo wykonane.
using System;
namespace composition
{
public interface IVehicle
{
int Fuel { get; }
void Drive();
void Refuel(int fuel);
}
public interface IEngine
{
int RotationSpeed { get; }
void ChangeRotationSpeed(int rotation);
}
public class Engine:IEngine
{
public int RotationSpeed { get; private set; }
public Engine(int rotation)
{
RotationSpeed = rotation;
}
public void ChangeRotationSpeed(int rotation)
{
if (rotation<=0)
{
throw new Exception("Bad rotation number");
}
RotationSpeed = rotation;
}
}
public class Vehicle : IVehicle
{
private readonly IEngine _engine;
public int Fuel { get; private set; }
public Vehicle(IEngine engine)
{
_engine = engine;
}
public void Refuel(int fuel)
{
Fuel = fuel;
}
public void Drive()
{
if (_engine.RotationSpeed == 0)
{
throw new Exception("No fuel");
}
Fuel--;
_engine.ChangeRotationSpeed(Fuel*13);
}
}
public class Plane : Vehicle
{
public Plane(IEngine engine):
base(engine)
{
}
}
public class Car : Vehicle
{
public Car(IEngine engine) :
base(engine)
{
}
}
public class Boat : Vehicle
{
public Boat(IEngine engine) :
base(engine)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
IVehicle boat = new Boat(new Engine(100));
boat.Refuel(200);
while (boat.Fuel != 0)
{
boat.Drive();
Console.WriteLine(boat.Fuel);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.ReadKey();
}
}
}
}