策略模式

非常普遍的“策略模式”就不多介绍了,下面是一个简单的案例,通过接口修改过来的,命名可能不是太规范,请谅解。呵呵

策略模式应该的场景:

简单的理解一下,通过你传什么对象什么值,做什么事,这就是策略。

类图如下:

一个Abstract,抽象类IBack,两个派生类,CellBack,CellBackB,然后一个重要的策略类,就完成了。

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace CA_OOO_Demo001
 7 {
 8     /// <summary>
 9     /// 定义一个回调接口
10     /// </summary>
11     abstract class IBack 
12     {
13       public  abstract void CellBackMethod();
14     }
15 
16     class CellBack : IBack
17     {
18 
19         public override void CellBackMethod()
20         {
21             Console.WriteLine("Thi is CellBack Method!A");
22         }
23     }
24 
25     class CellBackB : IBack
26     {
27 
28         public override void CellBackMethod()
29         {
30             Console.WriteLine("Thi is CellBack Method!B");
31         }
32     }
33 
34     class Controller
35     {
36         public IBack CellbackObj = null;
37 
38         public Controller(IBack obj)
39         {
40             this.CellbackObj = obj;
41         }
42 
43         public void Start()
44         {
45             Console.WriteLine("键盘按下回车键,条件成立下执行回调方法!");
46             if (ConsoleKey.Enter == Console.ReadKey(true).Key)
47             {
48                 CellbackObj.CellBackMethod();
49             }
50         }
51 
52     }
53 
54 
55     class InterfaceCellBack
56     {
57         static void Main(string[] args)
58         {
59             Controller cOjb = new Controller(new CellBack());
60             Controller cOjb2 = new Controller(new CellBackB());
61             cOjb.Start();
62             cOjb2.Start();
63         }
64     }
65 }
原文地址:https://www.cnblogs.com/p_db/p/2581304.html