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

推荐订阅源

腾讯CDC
The Cloudflare Blog
IT之家
IT之家
V
V2EX
雷峰网
雷峰网
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
Stack Overflow Blog
Stack Overflow Blog
博客园 - Franky
Engineering at Meta
Engineering at Meta
S
SegmentFault 最新的问题
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
小众软件
小众软件
博客园 - 叶小钗
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
A
About on SuperTechFans
B
Blog
月光博客
月光博客
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI

博客园 - 宝气狗

【摄影】2008年06月07日西塘 【摄影】2008年05月24日大明山 2007年11月——感受黄山,天下无山。 将基础数据类型与字节数组相互转换 托管/非托管类型对照 【数据库】遍历XML根下的一级节点 - 宝气狗 - 博客园 Enterprise Library中缓存过期策略探究 css中的nowrap 2007年9月15日 九溪-五云山-梅家坞之行 宝气狗的新闻博开始使用http://webbased.cn [设计模式] 22.State 状态模式 [设计模式] 23.Strategy 策略模式 值类型装箱拆箱需要注意的地方 CLR如何控制类型中字段的布局 MSIL指令速查 内存一致性问题(续一) 内存一致性问题 如何循序渐进向DotNet架构师发展 关于将Queue中的数据拼接成xml的经验
[设计模式] 15.Command 命令模式
宝气狗 · 2007-08-13 · via 博客园 - 宝气狗

我的理解:
命令池(采用堆或栈皆可)维护着一组命令集合。
只要这些命令实现同个命令接口或者命令抽象类,就能够被命令池依次执行。

class App
{
    
static void Main()
    
{
        
//命令模式:将无论哪个实例的方法抽象成对应的命令放入命令池。命令池会自动执行。
        Printer printer = new Printer();
        Scanner scanner 
= new Scanner();
        PrintCommand pc 
= new PrintCommand(printer);
        ScanCommand sc 
= new ScanCommand(scanner);
        CommandQueue.Instance.Enquee(pc);
        CommandQueue.Instance.Enquee(sc);
    }

}

//ICommand命令池,计时器每过一段时间取出一个命令执行
public class CommandQueue : Queue<ICommand>
{
    
单例
    
    
private Timer _t;

    
private CommandQueu()
    
{
        _t 
= new Timer(new TimerCallback(Execute), null5000200);
    }


    
private void Execute(object obj)
    
{
        
if (this.Count > 0)
        
{
            ICommand cmd 
= this.Dequeue();
            cmd.Execute();
        }

    }

}

//所有命令的抽象,这里使用接口比较好
public interface ICommand
{
    
void Execute();
}

//打印机打印的命令
public class PrintCommand : ICommand
{
    
private Printer _printer;
    
public PrintCommand( Printer printer)
    
{
        _printer 
= printer;
    }

    
public virtual void Execute()
    
{
        _printer.Print();
    }

}

//扫描仪扫描的命令
public class ScanCommand : ICommand
{
    
private Scanner _scanner;
    
public ScanCommand(Scanner scanner)
    
{
        _scanner 
= scanner;
    }

    
public virtual void Execute()
    
{
        _scanner.Scan();
    }

}

//打印机提供打印方法
public class Printer
{
    
public void Print()
    
{
        Console.WriteLine(
"Print.");
    }

}

//扫描仪提供扫描方法
public class Scanner
{
    
public void Scan()
    
{
        Console.WriteLine(
"Scan.");
    }

}