
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 ********
{
/// <summary>
/// 通信类型
/// </summary>
public enum CommunicationType
{
Ethernet,//TCP
Serialport,//RS485
};
}
这篇博客介绍了如何通过工厂模式来创建和切换TCP和RS485两种通信方式。首先定义了一个抽象基类`ACommunication`,然后创建了它的两个派生类`CmdTcp`和`CmdSerialport`分别对应TCP和485通信。工厂类`CommunicationFactory`根据`CommunicationType`枚举值动态实例化所需的通信类,实现了通信方式的动态选择。
1万+

被折叠的 条评论
为什么被折叠?



