///
/// 一般類別: Adventurer (Product)
///
public class Adventurer
{
// virtual: 虛擬方法
public virtual string getType()
{
}
}
///
/// Archer 繼承 Adventurer (ConcreteProduct)
///
public class Archer : Adventurer
{
// override: 覆寫 getType 方法
public override string getType()
{
string message = "I am a Archer";
System.Console.WriteLine(message);
return message;
}
}
///
/// Warrior 繼承 Adventurer (ConcreteProduct)
///
public class Warrior : Adventurer
{
// override: 覆寫 getType 方法
public override string getType()
{
string message = "I am a Warrior";
System.Console.WriteLine(message);
return message;
}
}
///
/// TrainingCamp (SimpleFactory)
///
public class TrainingCamp
{
public Adventurer trainAdventurer(string type)
{
switch (tpye)
{
case "archer":
System.Console.WriteLine("Training a Archer");
return new Archer();
break;
case "warrior":
System.Console.WriteLine("Training a Warrior");
return new Warrior();
break;
default:
}
}
}
public class SampleCode
{
public void Demo()
{
// 創建 TrainingCamp
TrainingCamp trainingCmap = new TrainingCamp();
// 帶入不同的參數 archer / warrior
Adventurer memberA = trainingCmap.trainAdventurer("archer");
Adventurer memberB = trainingCmap.trainAdventurer("warrior");
System.Console.WriteLine(memberA.getType());
System.Console.WriteLine(memberB.getType());
}
}
Ref
- 7 天學會設計模式-設計模式也可以這樣學
- 大話設計模式
沒有留言:
張貼留言