您的位置:首页 > 娱乐 > 明星 > 设计模式-策略模式

设计模式-策略模式

2024/10/6 5:56:37 来源:https://blog.csdn.net/qq_58870988/article/details/141192799  浏览:    关键词:设计模式-策略模式

概述

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


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

策略模式

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小时时间

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com