class Object with Dependency Injection
Salih Dincer
salihdb at hotmail.com
Sun Jun 18 14:37:10 UTC 2023
Hi, below is an example of DI-dependency injection with 3
versions nested in the code. If you remove the leading //
characters, you will not get the "no property `deliver` for
`service` of type `object.Object`" error. Because version-2I
with interface wants its methods to depend on Object..
```d
//abstract class /* toggle-code
interface //* ^---version 2A */
ITransport
{
string deliver();
}
class Ship : ITransport
{
override string deliver()
{
return "Ship Deliver";
}
}
class Truck : ITransport
{
override string deliver()
{
return "Truck Deliver";
}
}
abstract class Logistics
{
ITransport createTransport();
auto operations()
{
return createTransport.deliver();
}
}
class RoadLogistics : Logistics
{
override ITransport createTransport()
{
return new Truck();
}
}
class SeaLogistics : Logistics
{
override ITransport createTransport()
{
return new Ship();
}
}
import std.stdio;
void main()
{
// DI version 1:
auto sl = new SeaLogistics;
auto rl = new RoadLogistics;
auto logistics = [ sl, rl ];
foreach(deliver; logistics)
{
auto str = deliver.operations();
str.length.writeln(": ", str);
}
import std.range : repeat;
"÷ ".repeat(9).writefln!"%-(%s%)";
// A->I version 2:
auto truck = new Truck;
auto ship = new Ship;
auto services = [ truck, ship ];
foreach(service; services)
{
auto str = service.deliver();
str.length.writeln(": ", str);
}
}
```
Maybe using an abstract class instead of interface or not using
auto will solve the problem, but I can't accept the situation! I
wonder what makes the interface special?
SDB at 79
More information about the Digitalmars-d-learn
mailing list