2017年7月10日 星期一

GoF - Simple Factory

  • GoF (2)
    • Creational Patterns 
  • UML
  • Code
    • 實作 Adventurer
    
    /// 
    /// 一般類別: Adventurer (Product)
    /// 
    public class Adventurer
    {
        // virtual: 虛擬方法
        public virtual string getType()
        {
    
        }
    }
    
    
    • 實作 Archer
    
    /// 
    /// 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
    
    /// 
    /// 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
    
    /// 
    /// 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:
            }
        } 
    }
    
    
    • Sample Code
    
    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 天學會設計模式-設計模式也可以這樣學
  • 大話設計模式




沒有留言:

張貼留言