簡單的InterFace 簡單工廠模式體驗

InterFace

 

 

上課的時候老師介紹的InterFace介紹

回來在實做一次

建立一個

/// <summary>
/// IFly介面
/// </summary>

public interface IFly
{
    string flying();
}

 

建立類別

 

/// <summary>
/// 小鳥類別
/// </summary>

public class Bird : IFly
{
    public Bird()
    {
  //
  // TODO: 在此加入建構函式的程式碼
  //
    }


    IFly 成員
}



/// <summary>
/// 超人類別
/// </summary>

public class SuperMan:IFly
{
    public SuperMan()
    {
  //
  // TODO: 在此加入建構函式的程式碼
  //
    }


    IFly 成員
}

 

 

 

建立工廠

/// <summary>
/// 飛飛工廠
/// </summary>

public class FlyFactory
{
    public FlyFactory()
    {

    }

    public static IFly CreateFly(FlyType fly)
    {
        IFly f = null;
        switch (fly)
        {
            case FlyType.Bird:  
                f = new Bird(); break;
            case FlyType.SuperMan:  
                f = new SuperMan(); break;
        }

        return f;
    }

    public enum FlyType
    {
        SuperMan,Bird
    }

}

 

 

實作

    protected void Page_Load(object sender, EventArgs e)
    {
        IFly f = FlyFactory.CreateFly(FlyFactory.FlyType.Bird);
        System.Web.HttpContext.Current.Response.Write(f.flying());
    }