(200-07-16) C#.NET 靜態 Method 工廠模式 (Static Factory)

摘要:(200-07-16) C#.NET 工廠模式 (Static Factory)

IHello 介面 intfacecspattern.rar

 

using System;
namespace cspattern
{
   public interface IHello
    {
        string getHello();
        string Message { set; }
    }
}

實作的IHello的類別 1

 

using System.Text;

namespace cspattern
{
    public class EngHello : cspattern.IHello
    {
      //Data Field
        private String _message;

        public String Message
        {
            set {
                _message = value;
            }
          
        }
      //講英文打招呼功能
      public String getHello()
      {
          return   _message+" Hello World!!";
           
      }
      //屬性

    }
}

實作的IHello的類別 2

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cspattern
{
    public class JaHello : cspattern.IHello
    {
        //Data Field
        private String _message;

        public String Message
        {
            set
            {
                _message = value;
            }

        }
        //講英文打招呼功能
        public String getHello()
        {
            return _message + " ブログのデザインを!!";

        }
        //屬性

    }
}

實作的IHello的類別 3

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cspattern
{
    public class TWHello : cspattern.IHello
    {
        //Data Field
        private String _message;

        public String Message
        {
            set
            {
                _message = value;
            }

        }
        //講英文打招呼功能
        public String getHello()
        {
            return _message + " 世界和平!!";

        }
        //屬性

    }
}

靜態工廠

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cspattern
{
    public class HelloFactory
    {
        //非關物件(共用)
        public static IHello createHello(HelloType type)
        {
            //通通使用介面
            IHello hello = null;
            switch (type)
            {
                case HelloType.English:
                    hello = new EngHello();
                    break;
                case HelloType.Japan:
                    hello = new JaHello();
                    break;
                case HelloType.Taiwan:
                    hello = new TWHello();
                    break;
            }
            return hello;
        }
    }

    //類型
    public enum HelloType
    {
        English,Taiwan,Japan
    }
}