Search code examples
oopdesign-patternssoftware-designcar-analogy

OOP design : Car - Connection between Tank and Engine


I'm not sure whether I'm violating OOP conepts insanely.

Say there is a Carclass which "has" an Engine and a Tank.

When the Engine is operating , it will take oil from the Tank (say unit by unit per a cycle though oil is uncountable)

How should the Engine get Oil from the Tank ? (When both are fields of Car?)

Actually an Engine should be continually " Supplied" oil rather than "gets" oil.
There should be "OilCirculatingSystem" which gets Oil from the Tank
and supplies to Engine.
How can I model this system in classes ?
Is there a suitable Design Pattern? enter image description here

** * Edit : Simply ,how to have an "Flow of Oil" from Tank to Engine ? (Is it Oil's responsibility to flow from the Tank to Engine when a valve is opened ?


Solution

  • I'm sorry if it fries the brain. Implementation of methods is missing but you get the idea I hope.

    class Tank
    {
        Oil oil;
    
        public Tank(OilPipe pipe)
        {
            pipe.OilNeeded += new EventHandler<OilNeededEventArgs>(pipe_OilNeeded);
        }
    
        public void FillOil(Oil oil) { }
    
        void pipe_OilNeeded(object sender, OilNeededEventArgs e)
        {
            e.Oil = oil.SubtractLiters(5);
        }
    }
    
    class OilPipe
    {
        public event EventHandler<OilNeededEventArgs> OilNeeded;
    
        public Oil SuckOil();
    }
    
    class Piston
    {
        public void Move() { }
    }
    
    class Oil
    {
        public Energy Burn() { }
    }
    
    class Energy
    {
        public void Push(Piston piston) { }
    }
    
    class Engine
    {
        OilPipe oilPipe;
    
        public Engine(OilPipe oilPipe, Piston piston)
        {
            this.oilPipe = oilPipe;
        }
    
        public void MovePiston()
        {
            Oil oil = oilPipe.SuckOil();
            Energy energy = Burn(oil);
            energy.Push(piston);
        }
    }
    
    class Car
    {
        Engine engine;
    
        public Car(Engine engine, Tank tank)
        {
    
        }
    
        public void Accelerate()
        {            
             engine.MovePiston();
        }
    }