Above answers covers your Question comprehensively. This type of requirements provides an opportunity to Programmer to improve their Object Oriented skills.
Please consider below "Design Principle" whenever you come across "Object Oriented Programming".
"
Program to an interface, not an implementation."
- From the wonderful Book - "
Head First Design Patterns" - By wonderful writers Eric Freeman and Elisabeth Freeman.
Lets define an Interface
IWay
.
public interface IWay
{
string getData();
}
Now define a Class -
Road
, which inherits the Interface -
IWay
.
public class ROAD: IWay
{
public string getData()
{
return "Marlton Road";
}
}
Lets define a Class-
PATH
, which too inherits the Interface -
IWay
.
public class PATH:IWay
{
public string getData()
{
return "Tagore Path";
}
}
It's time to declare and define
FETCH
Method. It will look like below.
public IWay FETCH(bool flag)
{
IWay objectToReturn = null;
if (flag)
{
objectToReturn = new ROAD();
}
else
{
objectToReturn = new PATH();
}
return objectToReturn;
}
if you observe return Type of
Fetch
method is Type of Interface
IWay
. And method
Fetch
will instantiate object of Interface
IWay
by either of your Class based on your condition.
One more Design Principle from "
Head First Design Patterns" Book is as below.
"No matter where you work, what you're building, or what language you are programming in, what's the one true constant that will be with you always?"
Answer is - CHANGE
Lets assume in future you get one more Entity called as "
STREET".
In that case all you have to do is as below.
public class STREET : IWay
{
public string getData()
{
return "Canal Street";
}
}
Hope this information helps you. :). Thank you for posting such a good Question.
Updated - Reeason to mention name of Book - "
Head First Design Patterns" here is to give a sincere credit to wonderful writers Eric Freeman and Elisabeth Freeman for their wonderful "
Design Principles".