策略模式:定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化; 使用的关键点是面对对象、面向接口编程。举个例子,以武士可以不断更换武器为例子背景:
策略模式实现步骤一:定义抽象策略类
1 interface IStrategy
2 {
3 void fighting();
4 }
策略模式实现步骤二:实现具体策略类
1 class Bow:IStrategy
2 {
3 public void fighting()
4 {
5 Console.WriteLine("向敌人放冷箭中……");
6 }
7 }
1 class Knife:IStrategy
2 {
3 public void fighting()
4 {
5 Console.WriteLine("使用刀作为武器…");
6 }
7 }
1 class Cannon:IStrategy
2 {
3 public void fighting()
4 {
5 Console.WriteLine("加农炮轰击敌人中……");
6 }
7 }
策略模式实现步骤三:定义环境类
1 class Context
2 {
3 private IStrategy _strategy;
4 public Context(IStrategy s)
5 {
6 this._strategy = s;
7 }
8 public void fighting()
9 {
10 this._strategy.fighting();
11 }
12 }
//调用
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Context context;
6 context = new Context(new Knife());
7 Console.WriteLine("选择武器为刀:");
8 context.fighting();
9 Console.WriteLine();
10 context = new Context(new Bow());
11 Console.WriteLine("选择武器为弓:");
12 context.fighting();
13 Console.WriteLine();
14 context = new Context(new Cannon());
15 Console.WriteLine("选择武器为加农炮:");
16 context.fighting();
17 Console.WriteLine();
18 }
19 }
适配器模式:是在想使用一个已经存在的类,但是他的接口并不符合要求,因为在编码过程中要遵循对扩展开放,对修改关闭的原则,所以不能对原有的类进行修改,这时便需要使用适配器模式,将原有的类适配成自己需要的形式。有类适配器和对象适配器两种适配器。举个简单的例子,以原本有一只神鹿只会快速跑,现在让它也会飞为背景,便能明白怎样使用了:
适配器模式实现步骤一:确定目标接口
1 interface ITarget
2 {
3 void run();
4 void fly();
5 }
适配器模式实现步骤二:确定被适配者
1 class Deer
2 {
3 public void run()
4 {
5 Console.WriteLine("我是一只神鹿,可带你游走四处。");
6 }
7 }
适配器模式实现步骤三:创建适配器(类适配器)
1 class classAdapter : Deer,ITarget //注意,这是采用继承的方式
2 {
3 public void fly()
4 {
5 Console.WriteLine("哇啊哦,我可以飞了!!");
6 }
7 }
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 ITarget flyDeer = new classAdapter();
6 flyDeer.run();
7 flyDeer.fly();
8 }
9 }
适配器模式实现步骤三:创建适配器(对象适配器)
1 class objectAdapter:ITarget
2 {
3 private Deer deer; //注意,这里是将目标作为适配器的一个成员
4 public objectAdapter(Deer d)
5 {
6 this.deer = d;
7 }
8 public void run()
9 {
10 deer.run();
11 }
12 public void fly()
13 {
14 Console.WriteLine("哇啊哦,我一样可以飞!!");
15 }
16 }
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 ITarget flyDeer = new objectAdapter(new Deer());
6 flyDeer.run();
7 flyDeer.fly();
8 }
9 }
策略模式优于适配器模式:
1.首先很大程度上简化了我们的代码。
2.降低了我们程序代码的耦合度,而低耦合正是面向对象的重要优点。