close
image
   1: interface IWeapon
   2: {
   3:     void Use();
   4: }

weapon 1: Sword

image

   1: class Sword : IWeapon
   2: {
   3:     public void Use()
   4:     {
   5:         Console.WriteLine("Sword");
   6:     }
   7: }

weapon 2: Axe

image

   1: class Axe:IWeapon
   2: {
   3:     public void Use()
   4:     {
   5:         Console.WriteLine("Axe");
   6:     }
   7: }

weapon 3: Club

image

   1: class Club:IWeapon
   2: {
   3:     public void Use()
   4:     {
   5:         Console.WriteLine("Club");
   6:     }
   7: }

Character Class

image

   1: class Character
   2: {
   3:     IWeapon weapon;
   4:     public void SetWeapon(IWeapon weapon)
   5:     {
   6:         this.weapon = weapon; 
   7:     }
   8:     public void Attack()
   9:     {
  10:         weapon.Use();
  11:     }
  12: }

Null Object

   1: class Null : IWeapon
   2:  {
   3:      public void Use()
   4:      {
   5:          Console.WriteLine("Null Object");
   6:      }
   7:  }

image

   1: class Null : IWeapon
   2: {
   3:     public void Use()
   4:     {
   5:         Console.WriteLine("Null Object");
   6:     }
   7: }

Console

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         IWeapon weapon = null;
   6:         Character ryan = new Character();
   7:  
   8:         while (true)
   9:         {
  10:             Console.WriteLine("Choose a weapon for ryan: 1.Sword 2. Axe 3. Club");
  11:             string input = Console.ReadLine();
  12:             switch(input)
  13:             {
  14:                 case "1":
  15:                     weapon = new Sword(); 
  16:                     break;
  17:                 case "2":
  18:                     weapon = new Axe();
  19:                     break;
  20:                 case "3":
  21:                     weapon = new Club();
  22:                     break;
  23:                 default:
  24:                     weapon = new Null();
  25:                     break;
  26:             }
  27:             ryan.SetWeapon(weapon);
  28:             ryan.Attack();
  29:         }
  30:     }
  31: }

image

 

Referces:

1. Null Object Pattern – Design Patterns (ep 18)

2. The Null Object Pattern

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()