This article is designing a Class Diagram for the ROLES Classes in a Star Wars game.
In this game, every person have his/her own role type which can be "Civilian", "Warrior", "Politician" ... etc.
The following claass diagram only shows how a "Warrior" use their weapons.
Picture 01 - The whole diagram
1. Realization
So I create a class named CWarrior, which implements the interface IWarrior.
The relation between them is Realization.That means CWarrior implements IWarrior.
public class CWarrior : IWarrior { private CCamp myCamp; //陣營 protected String myName; //名稱 /* cCamp */ public CCamp Camp { get { return myCamp; } set { myCamp = value; } } /* sName */ public String Name { get { return myName; } set { myName = value; } } /* 使用武器 */ public virtual void Use_Weapon() { Console.WriteLine("{0} 使用了武器。", myName); } }
We use a enum class named CCamp in CWarrior.
A warrior belongs to no or only one camp.
A camp can keep existing even when a warrior disappear.
So the relation between them is Aggregation.
public enum CCamp { Empire, Rebel_Alliance }
3. Generalization
Next step, we create two class CJedi and CSith , to generalize CWarrior.
We add an additional property : CWeapon Weapon (see 4.),
and a override method : Use_Weapon() to use Jedi's and Sith's special weapons.
The Generalization between a child class and a father class is showed in picture 04.
public class CJedi : CWarrior { public CWeapon Weapon; //武器 /* 使用武器 (改寫) */ public override void Use_Weapon() { Console.WriteLine("絕地武士 {0} 使用了武器 - {1}。", this.myName, this.Weapon); } } public class CSith : CWarrior { public CWeapon Weapon; //武器 /* 使用武器 (改寫) */ public override void Use_Weapon() { Console.WriteLine("西斯武士 {0} 使用了武器 - {1}。", this.myName, this.Weapon); } }
We use CWeapon in both CJedi and CSith.
In my opnion, the weapons cannot be used if the Jedi and Sith warriors all disappear.
So I use the Composition relation here.
That means CWeapon only exist or use with CJedi and CSith, other class can't use CWeapon.
Furthermore, one jedi/sith can only have one weapon, so the multiplicity is set to be 1 to 1.
public enum CWeapon { Laser_Gun, Light_Saber }
Test result ...
A warrior named "白兵" used his weapon.
output : 白兵 使用了武器。
A Jedi named "路克天行者" used his weapon.
output : 絕地武士 路克天行者 使用了武器 - Light_Saber。
A Sith named "達斯維達" used his weapon.
output : 西斯武士 達斯維達 使用了武器 - Light_Saber。
Reference :
http://www.webdsai.idv.tw/?p=2329
沒有留言:
張貼留言