c# 简单工厂模式,实现TCP和485的切换

c# 简单工厂模式,实现TCP和485的切换_第1张图片
1.先完成基类(父类)的代码,注意为抽象类:abstract;
2.TCP和485两个通信类作为基类的派生类;
3.工厂类实现两种通信方式的切换,下面附工厂类的代码,该类通常情况下是静态的,也可以不设。

public class CommunicationFactory
    {
        //ACommunication是抽象父类
        static ACommunication communication = null;
        //CommunicationType是通信类型类(看最下面的代码),Serialport代表选择了485
        static CommunicationType communicationType = CommunicationType.Serialport;

        public static ACommunication GetInstence()
        {
            if (communication != null)
                return communication;

            switch (communicationType)
            {
                case CommunicationType.Serialport:
                    communication = new CmdSerialport();
                    break;

                case CommunicationType.Ethernet:
                    communication = new CmdTcp();
                    break;

                default:
                    communication = new CmdSerialport();
                    break;
            }
  
            return communication;//注意返回类型,返回的是父类实例化对象
        }
    }


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

namespace ********
{
    /// 
    /// 通信类型
    /// 
    public enum CommunicationType
    {
        Ethernet,//TCP
        Serialport,//RS485
    };
}

你可能感兴趣的:(c#,简单工厂模式,开发语言)