How to implement this type of OOP structure?

I want to create a nice API (C #) to make it easier for people, I think I've seen this before and want to know how to do it:

MyNamespace.Cars car = null;

if(someTestCondition)
       car = new Honda();
else    
       car = new Toyota();

car.Drive(40);

      

Is it possible? If so, what should be done?

+1


source to share


7 replies


Interface Car
{
void Drive(int miles);
}

class Honda : Car
{
...
}
class Toyota : Car
{
...
}

      



+10


source


You can do this in several different ways. You can declare an abstract base class, or you can have an interface implemented by your object. I believe the preferred "C #" method should be interface. Something like:



public interface ICar
{
    public Color Color { get; set; }

    void Drive(int speed);
    void Stop();

}

public class Honda : ICar
{

    #region ICar Members

    public Color Color { get; set; }

    public void Drive(int speed)
    {
        throw new NotImplementedException();
    }

    public void Stop()
    {
        throw new NotImplementedException();
    }

    #endregion
}

public class Toyota : ICar
{
    #region ICar Members

    public Color Color { get; set; }

    public void Drive(int speed)
    {
        throw new NotImplementedException();
    }

    public void Stop()
    {
        throw new NotImplementedException();
    }

    #endregion
}

      

+6


source


I can see that everyone is causing interface / abstract base class changes. The pseudocode you have provided more or less implies that you already have this location.

I'll do something else:

You need to create a "CarFactory" which will return a specific implementation of your base class / interface. The Create method can take your test conditions as parameters so that you create the correct car.

EDIT: Here's a link from MSDN - http://msdn.microsoft.com/en-us/library/ms954600.aspx

EDIT: See comments on the other link.

+5


source


Create a class called Cars. Give it a Drive method. Extend this base class to your Honda and Toyota classes.

+1


source


namespace MyNameSpace
{
  public interface Cars
  {
    public void Drive(int miles);
  }
  public class Honda : Cars
  {
    public void Drive(int miles) { ... }
  }
  public class Toyota : Cars
  {
    public void Drive(int miles) { ... }
  }
}

      

0


source


Don't forget the namespace, also see my comment on the question about variable names

namespace MyNamespace {
    public interface Cars {
        void Drive(int speed);
    }

    public class Honda : Cars {
        public void Drive(int speed) { 
        }
    }
    public class Toyota : Cars {
        public void Drive(int speed) {

        }
    }
}

      

0


source


Create an abstract class called Cars with an abstract method called Drive (). Subclassing and adding implementations.

0


source







All Articles