Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your code does implement the pattern but not to the full extent which C# allows, in other words - you are not using the important benefits of the C# language.</p> <p>Here is an example of how you can do it better:</p> <pre><code> class Program { static void Main(string[] args) { var myEngineer = ProfessionFactory.CreateProffession&lt;Engineer&gt;(); var myDoctor = ProfessionFactory.CreateProffession&lt;Doctor&gt;(); myEngineer.EnginerringStuff(); myDoctor.HealingPeople(); var myEngineer2 = (Engineer)ProfessionFactory.CreateProffession("Engineer"); //using the other method I still have to cast in order to access Engineer methods. //therefore knowing what type to create is essential unless we don't care about engineer specific methods, //in that case we can do: var myEngineer3 = ProfessionFactory.CreateProffession("Engineer"); //which is useless unless we start involving reflections which will have its own price.. } public interface IProfessionFactory { IProfession CreateObj(); } public interface IProfession : IProfessionFactory { string ProfessionName { get; } } public abstract class ProfessionFactory : IProfessionFactory { public abstract IProfession CreateObj(); public static T CreateProffession&lt;T&gt;() where T:IProfessionFactory, new() { return (T)new T().CreateObj(); } public static IProfession CreateProffession(object dataObj) { if (dataObj == "Engineer") return CreateProffession&lt;Engineer&gt;(); if (dataObj == "Doctor") return CreateProffession&lt;Doctor&gt;(); throw new Exception("Not Implemented!"); } } public class Engineer : IProfession { public string ProfessionName { get { return "Engineer"; } } public IProfession CreateObj() { return new Engineer(); } public void EnginerringStuff() {} } public class Doctor : IProfession { public string ProfessionName { get { return "Doctor"; } } public IProfession CreateObj() { return new Doctor(); } public void HealingPeople() {} } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload