设计模式实践-策略模式

场景

使用不同策略封装命令

实现代码

命令封装接口

namespace DesignPatterns.Strategy
{
    /// <summary>
    /// 命令封装接口
    /// </summary>
    public interface IPacket
    {
        /// <summary>
        /// 分装数据
        /// </summary>
        /// <returns>数据对象</returns>
        void Packet();
    }
}

抽象命令封装类

namespace DesignPatterns.Strategy
{
    /// <summary>
    /// 命名打包抽象类
    /// </summary>
    public abstract class AbstractPacket
    {
        /// <summary>
        /// 命令长度
        /// </summary>
        protected int Len;

        /// <summary>
        /// 命令数组
        /// </summary>
        protected byte[] Datas = new byte[256];

        /// <summary>
        /// 获取命令长度
        /// </summary>
        /// <returns></returns>
        public int GetLen()
        {
            return this.Len;
        }

        /// <summary>
        /// 获取命令
        /// </summary>
        /// <returns></returns>
        public byte[] GetDatas()
        {
            return this.Datas;
        }
    }
}

命令A封装实现

namespace DesignPatterns.Strategy
{
    /// <summary>
    /// A命令打包类
    /// </summary>
    public class PacketA : AbstractPacket, IPacket
    {
        /// <summary>
        /// 打包命令
        /// </summary>
        public void Packet()
        {
            this.Len = 20;
            for (int i = 0; i < this.Len; i++)
            {
                this.Datas[i] = 0x00;
            }
        }
    }
}

命令B封装实现

namespace DesignPatterns.Strategy
{
    /// <summary>
    /// B命令打包类
    /// </summary>
    public class PacketB : AbstractPacket, IPacket
    {
        /// <summary>
        /// 打包命令
        /// </summary>
        public void Packet()
        {
            this.Len = 50;
            for (int i = 0; i < this.Len; i++)
            {
                this.Datas[i] = 0x10;
            }
        }
    }
}

相关调用

IPacket packetA = new PacketA();
IPacket packetB = new PacketB();
packetA.Packet();
packetB.Packet();
Console.WriteLine(((AbstractPacket)packetA).GetLen());
Console.WriteLine(((AbstractPacket)packetB).GetLen());      

Out:

20
50     

转载于:https://www.cnblogs.com/4thing/p/5734342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值