惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
腾讯CDC
爱范儿
爱范儿
Google DeepMind News
Google DeepMind News
V
V2EX
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
量子位
F
Fortinet All Blogs
G
Google Developers Blog
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
T
Tailwind CSS Blog
J
Java Code Geeks
S
SegmentFault 最新的问题
D
Docker
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
M
MIT News - Artificial intelligence
博客园 - 【当耐特】

博客园 - Charly

我的电影记录 再去听他的演唱会 学友12月29日广州演唱会 张学友十大粤语&十大国语金曲赏析 妈妈的第二次重生 随便谈谈最近参与的2个项目 中奖的幸运与不幸 设计模式学习笔记二十五——总结 Moss2007搜索服务配置,没有索引器和搜索配置页面报错问题解决 设计模式学习笔记二十四——Visitor模式 设计模式学习笔记二十三——TemplateMethod模式 设计模式学习笔记二十一——State模式 设计模式学习笔记二十——Memento模式 设计模式学习笔记十九——Observer模式 在MOSS 2007中调试WebPart 设计模式学习笔记十八——Mediator模式 设计模式学习笔记十七——Iterator模式 设计模式学习笔记十六——Interpreter模式 设计模式学习笔记十五——Command模式
设计模式学习笔记二十二——Strategy模式
Charly · 2007-08-24 · via 博客园 - Charly

动机:定义一系列算法,把它们一个个封装起来,并且使它们可互相替换。该模式使得算法可独立于使用它的客户而变化。

场景:设计一个自动投票程序,根据常用投票对象的计票策略不同,定义一系列不同自动投票策略,可根据投票对象策略选用适当的自动投票策略。

结构
Strategy模式结构图

代码

namespace DesignPattern.Strategy
{
    
public interface IVoteStrategy
    
{
        
void Vote();

        
// 统计投票情况
        void Stat();
    }


    
public class VoteStrategyA : IVoteStrategy
    
{
        
public void Vote()
        
{
        }

        
public void Stat()
        
{
        }

    }


    
public class VoteStrategyB : IVoteStrategy
    
{
        
public void Vote()
        
{
        }

        
public void Stat()
        
{
        }

    }


    
public class VoteStrategyC : IVoteStrategy
    
{
        
public void Vote()
        
{
        }

        
public void Stat()
        
{
        }

    }

}

namespace DesignPattern.Strategy
{
    
public class AutoVote
    
{
        
private IVoteStrategy strategy;

        
public AutoVote(IVoteStrategy strategy)
        
{
            
this.strategy = strategy;
        }


        
public IVoteStrategy Strategy
        
{
            
set
            
{
                
this.strategy = value;
            }

        }


        
public void Vote()
        
{
            
//
            strategy.Vote();
        }


        
public void Stat()
        
{
            
//
            strategy.Stat();
        }

    }

}

要点
        1、Strategy及其子类为组件提供了一系列可重用的算法,从而使得类型在运行时方便地根据需要在各个算法之间进行切换,所谓封装算法,支持算法的变化。
        2、本模式提供了用条件判断语句以外的另一种选择,消除条件判断语句,就是在解耦。含有许多条件判断语句的代码通常都需要本模式。
        3、与State模式类似,如果Strategy对象没有实例变量,那么各个上下文可以共享同一个Strategy对象,从而节省对象开销。

欢迎光临我的淘宝http://shop35795100.taobao.com,专营游戏点卡、电话卡及各类充值卡。

posted on 2007-08-24 00:25  Charly  阅读(600)  评论(1)    收藏  举报