Guest User

Untitled

a guest
Aug 20th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. Can anybody give a good example of what to use generic classes for?
  2. public class CatFactory
  3. {
  4. public Cat CreateCat()
  5. {
  6. return new Cat();
  7. }
  8. }
  9.  
  10. public class Factory<T> where T : new()
  11. {
  12. public T Create()
  13. {
  14. return new T();
  15. }
  16. }
  17.  
  18. // interface for included tools to build your furniture
  19. public interface IToolKit {
  20. string[] GetTools();
  21. }
  22.  
  23. // interface for included parts for your furniture
  24. public interface IParts {
  25. string[] GetParts();
  26. }
  27.  
  28. // represents a generic base class for IKEA furniture kit
  29. public abstract class IkeaKit<TContents> where TContents : IToolKit, IParts, new() {
  30. public abstract string Title {
  31. get;
  32. }
  33.  
  34. public abstract string Colour {
  35. get;
  36. }
  37.  
  38. public void GetInventory() {
  39. // generic constraint new() lets me do this
  40. var contents = new TContents();
  41. foreach (string tool in contents.GetTools()) {
  42. Console.WriteLine("Tool: {0}", tool);
  43. }
  44. foreach (string part in contents.GetParts()) {
  45. Console.WriteLine("Part: {0}", part);
  46. }
  47. }
  48. }
  49.  
  50. // describes a chair
  51. public class Chair : IToolKit, IParts {
  52. public string[] GetTools() {
  53. return new string[] { "Screwdriver", "Allen Key" };
  54. }
  55.  
  56. public string[] GetParts() {
  57. return new string[] {
  58. "leg", "leg", "leg", "seat", "back", "bag of screws" };
  59. }
  60. }
  61.  
  62. // describes a chair kit call "Fnood" which is cyan in colour.
  63. public class Fnood : IkeaKit<Chair> {
  64. public override string Title {
  65. get { return "Fnood"; }
  66. }
  67.  
  68. public override string Colour {
  69. get { return "Cyan"; }
  70. }
  71. }
  72.  
  73. public class Snoolma : IkeaKit<Chair> {
  74. public override string Title {
  75. get { return "Snoolma "; }
  76. }
  77.  
  78. public override string Colour {
  79. get { return "Orange"; }
  80. }
  81. }
  82.  
  83. var fnood = new Fnood();
  84. fnood.GetInventory(); // print out tools and components for a fnood chair!
Add Comment
Please, Sign In to add comment