Skip to content

Instantly share code, notes, and snippets.

@cemremengu
Last active December 14, 2015 10:19
Show Gist options
  • Save cemremengu/5070902 to your computer and use it in GitHub Desktop.
Save cemremengu/5070902 to your computer and use it in GitHub Desktop.
A factory class that uses generics
// Example usage: Apple myAppleVar = Fruit<Apple>.CreateInstance();
// ref: http://stackoverflow.com/questions/1380087/whats-the-correct-alternative-to-static-method-inheritance-c
public abstract class Fruit<T>
where T : Fruit<T>, new()
{
public static T CreateInstance()
{
T newFruit = new T();
newFruit.Initialize(); // Calls Apple.Initialize
return newFruit;
}
protected abstract void Initialize();
}
public class Apple : Fruit<Apple>
{
protected Apple() { }
protected override void Initialize() { ... }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment