设计模式-策略模式

概述

策略模式也是一种行为型的设计模式,它主要是定义一系列的算法封装起来,然后可以通过策略进行互换,提高代码的复用性可维护性质。其主要实现分为,策略接口,算法类,还有策略类通过扩展算法类来扩展算法,调用策略类来传入不同的算法,实现对应的接口方法


举例:小明要去外地,有汽车和火车两种方式,小明该如何选择,请设计实现。

策略模式

internal class Program
{
    private static void Main(string[] args)
    {
        IVehicle car = new Car();
        IVehicle train = new Train();
        //使用汽车
        Strategy S_car = new Strategy(car);
        S_car.TakeTime("2小时");
        //使用火车
        Strategy S_train = new Strategy(train);
        S_train.TakeTime("1小时");
    }
    public interface IVehicle//交通工具接口
    {
        void Time(string _time);
    }
    public class Car : IVehicle//汽车
    {
        public void Time(string _time)
        {
            Console.WriteLine($"使用汽车花费{_time}时间");
        }
    }
    public class Train : IVehicle//火车
    {
        public void Time(string _time)
        {
            Console.WriteLine($"使用火车花费{_time}时间");
        }
    }
    public class Strategy//策略类
    {
        private IVehicle vehicle;
        public Strategy(IVehicle vehicle)
        {
            this.vehicle = vehicle;
        }
        public void TakeTime(string time)
        {
            vehicle.Time(time);
        }
    }
}

输出结果

使用汽车花费2小时时间
使用火车花费1小时时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值