Linux下的设计模式——策略模式(StrategyPattern)深⼊浅出【建议新⼿收
藏】
⼀、策略模式简介
策略模式定义:是指定义了算法家族、分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使⽤算法的⽤户
策略模式优点:可以避免多重分⽀的if…el…和switch语句
策略模式的使⽤场景:
假如系统中有很多类,⽽他们的区别仅仅在于他们的⾏为不同。
⼀个系统需要动态的在⼏种算法中选择⼀种。
策略模式案例:
JDK中Comparator接⼝中的intcompare(To1,To2);⽅法,在Arrays、TreeMap⾥可以⾃定义排序规则
Spring中的Resource接⼝
Spring中InstantiationStrategy接⼝,主要对类进⾏初始化策略,有两个策略实现类,它们不是平级⽽是继承关系(策略模式中不同策
略也可以继承)
CglibSubclassingInstantiationStrategy:Cglib的初始⽅式
SimpleInstantiationStrategy:JDK的初始化⽅式
类图
⼆、简单代码案例
案例:购买东西有活动时,会有抵⽤券、返现、拼团等减免⾦额的策略
优惠策略抽象接⼝
publicinterfacePromotionStrategy{
/**
*执⾏优惠
*/
voiddoPromotion();
}
没有优惠
publicclassEmptyStrategyimplementsPromotionStrategy{
@Override
publicvoiddoPromotion(){
n("⽆促销活动");
}
}
抵⽤券
publicclassCouponStrategyimplementsPromotionStrategy{
@Override
publicvoiddoPromotion(){
n("领取优惠券,课程的价格直接减去优惠券⾯值抵扣");
}
}
返现
publicclassCashbackStrategyimplementsPromotionStrategy{
@Override
publicvoiddoPromotion(){
n("返现促销,返回的⾦额转到⽀付宝账号");
}
}
拼团
publicclassGroupBuyStrategyimplementsPromotionStrategy{
@Override
publicvoiddoPromotion(){
n("拼团,满20⼈成团,全团享受团购价格");
}
}
优惠活动
publicclassPromotionActivity{
PromotionStrategypromotionStrategy;
publicPromotionActivity(PromotionStrategypromotionStrategy){
ionStrategy=promotionStrategy;
}
/**
*执⾏优惠活动
*/
publicvoidexecute(){
otion();
}
}
测试⼀
publicstaticvoidmain(String[]args){
//618优惠券活动
PromotionActivityactivity618=newPromotionActivity(newCouponStrategy());
e();
//双11返现活动
PromotionActivityactivity1111=newPromotionActivity(newCashbackStrategy());
e();
}
测试⼆
publicstaticvoidmain(String[]args){
PromotionActivitypromotionActivity=null;
StringpromotionKey="COUPON";
if((promotionKey,"COUPON")){
promotionActivity=newPromotionActivity(newCouponStrategy());
}elif((promotionKey,"CASHBACK")){
promotionActivity=newPromotionActivity(newCashbackStrategy());
}//.......
e();
}
简单实现完发现还可以通过单例模式+简单⼯⼚模式简化代码,⽤唯⼀标志选择策略
⼯⼚类
publicclassPromotionStrategyFactory{
privatestaticfinalMap
privatestaticfinalPromotionStrategyNON_PROMOTION=newEmptyStrategy();
static{
PROMOTION_STRATEGY_(,newCouponStrategy());
PROMOTION_STRATEGY_(CK,newCashbackStrategy());
PROMOTION_STRATEGY_(UY,newGroupBuyStrategy());
}
privatePromotionStrategyFactory(){}
publicstaticPromotionStrategygetPromotionStrategy(StringpromotionKey){
PromotionStrategypromotionStrategy=PROMOTION_STRATEGY_(promotionKey);
returnpromotionStrategy==null?NON_PROMOTION:promotionStrategy;
}
privateinterfacePromotionKey{
StringCOUPON="COUPON";
StringCASHBACK="CASHBACK";
StringGROUPBUY="GROUPBUY";
}
}
测试
publicstaticvoidmain(String[]args){
StringpromotionKey="GROUPBUY";
PromotionActivitypromotionActivity=newPromotionActivity(motionStrategy(promotionKey));
e();
}
附上类结构图
三、简单代码⼆案例
案例:⽤户下单⽀付,可以选择多种⽀付渠道
⽀付抽象类
publicabstractclassPayment{
/**
*⽀付信息
*@return
*/
publicabstractStringgetName();
/**
*余额
*@paramuid
*@return
*/
protectedabstractdoublequeryBalance(Stringuid);
/**
*⽀付
*@paramuid
*@paramamount
*@return
*/
publicMsgResultpay(Stringuid,doubleamount){
if(queryBalance(uid)
returnnewMsgResult(500,"⽀付失败","余额不⾜");
}el{
returnnewMsgResult(200,"⽀付成功","⽀付⾦额:"+amount);
}
}
}
⽀付宝⽀付
publicclassAliPayextendsPayment{
@Override
publicStringgetName(){
return"⽀付宝";
}
@Override
protecteddoublequeryBalance(Stringuid){
return900;
}
}
京东⽩条
publicclassJDPayextendsPayment{
@Override
publicStringgetName(){
return"京东⽩条";
}
@Override
protecteddoublequeryBalance(Stringuid){
return500;
}
}
银联⽀付
publicclassUnionPayextendsPayment{
@Override
publicStringgetName(){
return"银联⽀付";
}
@Override
protecteddoublequeryBalance(Stringuid){
return120;
}
}
微信⽀付
publicclassWechatPayextendsPayment{
@Override
publicStringgetName(){
return"微信⽀付";
}
@Override
protecteddoublequeryBalance(Stringuid){
return256;
}
}
返回消息类
publicclassMsgResult{
privateintcode;
privateObjectdata;
privateStringmsg;
publicMsgResult(intcode,Objectdata,Stringmsg){
=code;
=data;
=msg;
}
@Override
publicStringtoString(){
return"MsgResult{"+
"code="+code+
",data="+data+
",msg='"+msg+'''+
'}';
}
}
订单类
publicclassOrder{
privateStringuid;
privateStringorderId;
privatedoubleamount;
publicOrder(Stringuid,StringorderId,doubleamount){
=uid;
d=orderId;
=amount;
}
publicMsgResultpay(StringpayKey){
Paymentpayment=(payKey);
n("欢迎使⽤"+e());
n("本次交易⾦额为:"+amount+",开始扣款...");
(uid,amount);
}
@Override
publicStringtoString(){
return"Order{"+
"uid='"+uid+'''+
",orderId='"+orderId+'''+
",amount="+amount+
'}';
}
}
⽀付策略⼯⼚
publicclassPayStrategy{
publicstaticfinalStringALI_PAY="AliPay";
publicstaticfinalStringJD_PAY="JDPay";
publicstaticfinalStringWECHAT_PAY="WchatPay";
publicstaticfinalStringUNION_PAY="UnionPay";
publicstaticfinalStringDEFAULT_PAY="AliPay";
privatestaticMap
static{
(ALI_PAY,newAliPay());
(JD_PAY,newJDPay());
(WECHAT_PAY,newWechatPay());
(UNION_PAY,newUnionPay());
(DEFAULT_PAY,newAliPay());
}
publicstaticPaymentget(StringpayKey){
if(!nsKey(payKey)){
(DEFAULT_PAY);
}
(payKey);
}
}
测试
publicclassPayStrategyTest{
publicstaticvoidmain(String[]args){
Orderorder=newOrder("1","2021110",1342.45);
MsgResultresult=(_PAY);
n(result);
}
}
附上类结构图:
四、总结
策略模式的优点:
策略模式符合开闭原则。
避免使⽤多重条件转移语句,如if…el…语句、switch语句。
使⽤策略模式可以提⾼算法的保密性和安全性。
策略模式的缺点:
客户端必须知道所有的策略,并且⽤户⾃⾏决定使⽤哪⼀个策略类。
代码中会产⽣⾮常多策略类,增加维护难度。
还等什么⼩编推荐⾃⼰的linuxC/C++语⾔交流群:【】整理了⼀些个⼈觉得⽐较好的学习书籍、视频资料共享在群⽂件⾥⾯,有需要的可以
⾃⾏添加哦!前100名进群领取,额外赠送⼀份价值199的C/C++、linux资料包含(视频教程、电⼦书、实战项⽬及代码),下⾯部分展
⽰。
本文发布于:2022-11-25 00:29:12,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/90/15206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |