2017年7月11日 星期二

GoF - Factory

  • GoF (3)
    • Creational Patterns 
  • UML
  • Code
    • 實作 Adventurer
    
    /// 
    /// interface: Adventurer (Product)
    /// 
    public interface IAdventurer
    {
        // 方法
        string getType();
    }
    
    
    • 實作 Archer
    
    /// 
    /// Archer 繼承 interface Adventurer (ConcreteProduct)
    /// 
    public class Archer : IAdventurer
    {
        // 實作 getType 方法
        public string getType()
        {
            string message = "I am a Archer";
            System.Console.WriteLine(message);
            return message;
        }
    }
    
    
    • 實作 Warrior
    
    /// 
    /// Warrior 繼承 interface Adventurer
    /// 
    public class Warrior : IAdventurer
    {
        // 實作 getType 方法
        public string getType()
        {
            string message = "I am a Warrior";
            System.Console.WriteLine(message);
            return message;
        }
    }
    
    
    • 實作 TrainingCamp
    
    /// 
    /// interface: TrainingCamp (Factory)
    /// 
    public interface ITrainingCamp 
    {
        Adventurer trainAdventurer();
    }
    
    
    • 實作 ArcherTrainingCmap
    
    /// 
    /// ArcherTrainingCmap 繼承 interface ITrainingCamp (ConcreteFactory)
    /// 
    public class ArcherTrainingCmap : ITrainingCamp
    {
        public Adventurer trainAdventurer()
        {
            System.Console.WriteLine("train a Archer");
            return new Archer();
        }
    }
    
    
    • 實作 WarriorTrainingCmap
    
    /// 
    /// WarriorTrainingCmap 繼承 interface ITrainingCamp (ConcreteFactory)
    /// 
    public class WarriorTrainingCmap : ITrainingCamp
    {
        public Adventurer trainAdventurer()
        {
            System.Console.WriteLine("train a Warrior");
            return new Warrior();
        }
    }
    
    • Sample Code
    
    public class SampleCode 
    {
        public void Demo()
        {
            // Archer Training Camp
            TrainingCamp trainingCmap = new ArcherTrainingCamp();
            Adventurer memberA = trainingCmap.trainAdventurer();
    
            // Warrior Training Camp
            TrainingCamp trainingCmap = new WarriorTrainingCmap();        
            Adventurer memberB = trainingCmap.trainAdventurer();
    
            System.Console.WriteLine(memberA.getType());
            System.Console.WriteLine(memberB.getType());
        }
    }
    
Ref
  • 7 天學會設計模式-設計模式也可以這樣學
  • 大話設計模式




沒有留言:

張貼留言