Slash18

Factory

Jun 23rd, 2016
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | None | 0 0
  1.  
  2. //    Full Tutorial on indiedevart.wordpress.com
  3.  
  4. using System;
  5. namespace Factory
  6. {
  7.  
  8.     public interface IFactory
  9.     {
  10.         void Demage(int dmg);
  11.     }
  12.  
  13.     public class EnemyType1 : IFactory
  14.     {
  15.         int _health=100;
  16.         public void Demage(int dmg)
  17.         {
  18.             _health -= dmg;
  19.             Console.WriteLine("EnemyType1 health: " + _health.ToString());
  20.         }
  21.     }
  22.  
  23.     public class EnemyType2 : IFactory
  24.     {
  25.         int _health = 200;
  26.         public void Demage(int dmg)
  27.         {
  28.             _health -= dmg;
  29.             Console.WriteLine("EnemyType2 health: " + _health.ToString());
  30.         }
  31.     }
  32.  
  33.     public abstract class EnemyFactory
  34.     {
  35.         public abstract IFactory InstantiateEnemy(int type);
  36.  
  37.     }
  38.  
  39.     public class InstantiateEnemyFactory : EnemyFactory
  40.     {
  41.  
  42.         public override IFactory InstantiateEnemy(int type)
  43.         {
  44.             switch (type)
  45.             {
  46.                 case 1:
  47.                     return new EnemyType1();
  48.                 case 2:
  49.                     return new EnemyType2();
  50.                 default:
  51.                     throw new ApplicationException(string.Format("Wrong number"));
  52.             }
  53.         }
  54.  
  55.     }
  56.  
  57.  
  58.     class Program
  59.     {
  60.         static void Main(string[] args)
  61.         {
  62.  
  63.             int type = new Random().Next(1, 1000) % 2+1;
  64.  
  65.             EnemyFactory factory = new InstantiateEnemyFactory();
  66.  
  67.             IFactory newEnemy= factory.InstantiateEnemy(type);
  68.             newEnemy.Demage(20);
  69.  
  70.             type = new Random().Next(1, 2000)%2+1;
  71.  
  72.             IFactory newEnemy2 = factory.InstantiateEnemy(type);
  73.             newEnemy2.Demage(20);
  74.  
  75.             Console.ReadKey();
  76.  
  77.         }
  78.     }
  79. }
Add Comment
Please, Sign In to add comment